Java Syntax: object creation | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Java Syntax: object creation

Hello, i like to know why i need to put the class name twice in the line. For example Classtest: Classtest objname = new Classtest(); Thank you

7th Jun 2018, 3:14 AM
Exthase Original (Anvil of Darkness)
Exthase Original (Anvil of Darkness) - avatar
8 Answers
+ 4
Let's look at each side of the = sign. The left side: Say, you want to declare an integer a, you write for instance int a = 0; The int on the left side is to tell the system the data type of your newly declared variable. So Classtest objname tells the system that the variable objname is of the data type Classtest. The right side: This synthax, you will just have to know. Any object of a class is created using the new operator and a contructor of a class. Now, the thing is that a constructor of a class ALWAYS has the same name as the class itself. That is why to actually create the variable objname we do new Classtest() where Classtest() is a constructor of the class Classtest...
7th Jun 2018, 3:29 AM
cyk
cyk - avatar
+ 4
Exthase Original (Anvil of Darkness) You are very welcome ☺... I don't understand your second question. To ever change what?
7th Jun 2018, 3:41 AM
cyk
cyk - avatar
+ 2
Good question. objname is declared to be of type Classtest, in the first use of Classtest. objname is assigned a value, an instance of Classtest, which is being created new, in the second use of Classtest. Now I can declare, Classtest mytest = objname; See the variations? Don't want to go into subclasses and polymorphism. But that's a classic scenario as well when you get to that level.
7th Jun 2018, 3:33 AM
Minnie Mouse
Minnie Mouse - avatar
+ 1
no I think I completly understand it now. Thank you very much
7th Jun 2018, 3:43 AM
Exthase Original (Anvil of Darkness)
Exthase Original (Anvil of Darkness) - avatar
+ 1
So you can do stuff like List<String> array = new ArrayList<>(); List<String> linked = new LinkedList<>(); Both will have same methods, but their internal structure will be different.
7th Jun 2018, 6:31 AM
BlazingMagpie
BlazingMagpie - avatar
0
ahhh it sets the datatype. is there a way or need to ever change that to... something else?
7th Jun 2018, 3:31 AM
Exthase Original (Anvil of Darkness)
Exthase Original (Anvil of Darkness) - avatar
0
thank you very much for this long text and your time. i appreciate it. =)
7th Jun 2018, 3:33 AM
Exthase Original (Anvil of Darkness)
Exthase Original (Anvil of Darkness) - avatar
0
minne mouse, and thank you too for your time
7th Jun 2018, 3:44 AM
Exthase Original (Anvil of Darkness)
Exthase Original (Anvil of Darkness) - avatar