New course! Every coder should learn Generative AI!
Try a free lesson+ 2
Why do we write the class name twice while creating object in java, like Vehicle bugatti = new Vehicle.
I want to know what does these two class name means, one before the object name and then after new keyword. (JAVA)
4 Answers
+ 9
The second class name which is after new keyword, is actually a constructor name which is there in the program by default.
I hope you understand
+ 4
Firstly to declare the type and secondly to invoke the constructor.
+ 2
The left side i.e, Vehicle bugatti means create a object called bugatti of type Vehicle, like same as "int i" or "String s".
The right side i.e, new Vehicle(); is to store everything the class Vehicle has in the object bugatti like same as "8, 10" or "Science is Cool".
+ 2
The constructor have to have the same name like the class.
So you have a class and inside a constructor:
public class MyClass{
//constructor
public MyClass(){
}
}
And when you create an object you normally call the constructor via new.
new MyClass() calls the constructor, which returns an instance of MyClass.
In your example bugatti is a variable from type Vehicle. The constructor returns an instance of Vehicle which is assigned o bugatti.