It seems redundant to type: 'Animal dog = new Animal(); ' instead of just 'Animal dog;'. Why was Java designed that way? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

It seems redundant to type: 'Animal dog = new Animal(); ' instead of just 'Animal dog;'. Why was Java designed that way?

We should be able to declare a new object based on a class by typing (for example) 'Animal dog;'. Is there a legitimate reason Java was designed to require the typing of 'Animal dog = new Animal();' which seems to be twice as much typing as should be needed?

20th Nov 2017, 9:36 AM
Zwingo
6 Answers
+ 12
The new keyword indicates an object creation and therefore the first example assign the new created Animal object to the variable named dog. It's an example of variable initialization and shorthand of the following 2 statements: Animal dog; // declare dog = new Animal(); // assign The latter is a simple variable declaration without any assignment and its value is null. Do you notice the difference here? 😉
20th Nov 2017, 10:11 AM
Zephyr Koo
Zephyr Koo - avatar
+ 3
It is needed to initialize the object. new Dog() means: Call the default constructor of the class Dog, to create new instance of that class. The default constructor may look like that: class Dog { String color; // Default constructor Dog() { color = black; } // Custom constructor Dog(String color) { this.color = color; } } Then whenever you create a dog using the default constructor (Dog()), the dog will be black by default. But, if you say: Dog newDog = new Dog("brown"); // calls the custom constructor Then you'll have a brown dog.
20th Nov 2017, 1:02 PM
Boris Batinkov
Boris Batinkov - avatar
+ 2
maybe to confirm that it is not enum but an object
20th Nov 2017, 9:53 AM
shobhit
shobhit - avatar
+ 2
sometimes you don't want to assign it, because you may need it to be null (a special value indicating something) or you want to assign there an existing animal from another variable, returned by a method...
20th Jan 2018, 6:10 PM
michal
+ 2
@michal, yes. Or you can assign values with setter methods.
20th Jan 2018, 7:33 PM
Boris Batinkov
Boris Batinkov - avatar
+ 1
Animal dog means that variable dog will hold refference to Animal object. new Animal() means that you creating a new object of Animal class. But this variable could also hold refference to an object that is already created. in that case, you dont want to use new keyword because it is creating new object and you dont want that. So yes, this is like this because its necessary
20th Nov 2017, 10:33 AM
Bartek Nowacki
Bartek Nowacki - avatar