+ 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)

1st Jul 2020, 8:33 AM
Vishal Vishwajeet
Vishal Vishwajeet - avatar
5 Réponses
+ 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
1st Jul 2020, 10:47 AM
Piyush
Piyush - avatar
+ 4
Firstly to declare the type and secondly to invoke the constructor.
2nd Jul 2020, 9:48 PM
Sonic
Sonic - avatar
+ 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".
1st Jul 2020, 9:45 AM
Blue!!
Blue!! - avatar
+ 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.
1st Jul 2020, 10:59 AM
Denise Roßberg
Denise Roßberg - avatar
0
As the name of class and its constructor(which is invoked at the time of object creation) are same so the first class name is for calling the class and next class name after the new keyword is for invoking the constructor
24th Oct 2024, 2:18 PM
Asmi Dagar
Asmi Dagar - avatar