Java Syntax: object creation | Sololearn: Learn to code for FREE!

+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

8 Answers

New Answer

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

+4

Exthase Original (Anvil of Darkness) You are very welcome ☺... I don't understand your second question. To ever change what?

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

+1

no I think I completly understand it now. Thank you very much

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

0

ahhh it sets the datatype. is there a way or need to ever change that to... something else?

0

thank you very much for this long text and your time. i appreciate it. =)

0

minne mouse, and thank you too for your time