Answer the question
In order to leave comments, you need to log in
How to deal with constructors?
I started learning Java, got to the constructors and got stuck. I can't understand why Box catBox = new Box();
we write "Box" twice here?
What does the first and second mean, and how do you use the catBox variable then?
I would be grateful for available examples.
Answer the question
In order to leave comments, you need to log in
Your string is a declaration of a variable and an assignment of a value to it. Since there is no auto type inference in Java, you must specify the type of each variable.
Let's say Box aBox; you declared a variable of type Box named aBox. Now you can only assign it a value of type Box (an instance of the Box class, an implementation of the Box interface, or a descendant of the Box class).
And on the right, the actual creation of an instance of the Box class through the constructor
1) Box catBox; // объявили переменную с типом Box и именем catBox (просто объявили, в ней ничего нет)
2) new Box(); // создали новый объект типа Box (и бросили)
3) catBox = new Box(); // создали новый объект типа Box и сказали, что с ним можно пообщаться используя 3) переменную catBox
4) Box catBox = new Box(); // объявили переменную и сразу с ней связали объект
The first Box is the type of the declared variable.
Second Box - class instance is created by calling the default constructor.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question