There is a class Cars

 package sample.cars; public class Cars { public static void main(String[] args) { Car chevrolet = new Car(); } } 

And Car class

 package sample.cars; public class Car { //Как сделать так чтобы можно было не называть класс при создании объекта class Motor { public boolean isElectro = false; } } 

And I don't need to call the nested class inside the main method. And just refer to the class Motor for the very name of the class ie. so chevrolet.Motor.isElectro

  • one
    static class Motor { ? - gil9red
  • So what? This does not change the problem. - ishidex2

2 answers 2

No If there is an object, then it must have a type. Nameless classes do not happen.

You can do this: https://ideone.com/kLiZPn

 import java.util.*; import java.lang.*; import java.io.*; class Ideone { public static void main (String[] args) throws java.lang.Exception { Car chevrolet = new Car(); System.out.println(chevrolet.Motor.isElectro); } } class Car { static class Motor { public boolean isElectro = false; } public Motor Motor = new Motor(); } 

But I note that in Java it is customary to write fields and methods with a small letter, that is, not chevrolet.Motor.isElectro , but chevrolet.motor.isElectro . It is also customary to use getters and setters, but this is not the case at all.

    As an option chevrolet. m otor.isElectro

     public class Cars { public static void main(String[] args) { Car chevrolet = new Car(); System.out.println(chevrolet.motor.isElectro); } } public class Car { public Motor motor = new Motor(); class Motor { public boolean isElectro = false; } } 
    • What is different from my answer, except for the absence of static class? - Qwertiy
    • Your option is not bad at all, but it seems to me that within the context, the object engine cannot exist without a machine object. - Micah