Question on Constructor | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Question on Constructor

Why to use a constructor in java when you can initialize variables directly.? class hello{ int a =50; } class hello{ int a; hello(int d) { a=d; } }

9th Jan 2021, 1:22 AM
shrijith
shrijith - avatar
1 Answer
+ 3
Ok so with "int type" its a built in primitive type so when you store a value to a variable of type int instead of a refrenece being stored the actual value which is the number. With class type you create a class then use the new keyword followed by class constructor method this creates an instance of class. Once you do this a reference is stored in the variable which points/refers to the object on heap you can use the "." to access your objects methods and fields/variables ie. let's say you have one class Hello which has a field holding the value of 50 the way you would create an instance of this class would be the following.. Hello h = new Hello(); int i = h.a; System.out.print(i); Output// 50;
9th Jan 2021, 1:59 AM
D_Stark
D_Stark - avatar