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; } }
1 Resposta
+ 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;