Just given test example to illustrate the things
public class Hello {
Hello var1, var2;
public static void main(String[] args){
Hello h1 = new Hello();
h1.var1 = h1;
System.out.println("h1.var1 ---- "+ h1.var1);
Hello h2 = new Hello();
h1.var2 = h2;
System.out.println("h1.var2 ---- "+ h1.var2);
h1.var2 = h1.var1;
System.out.println("h1.var1 ---- "+ h1.var1);
System.out.println("h1.var2 ---- "+ h1.var2);
}
}
Output :-
h1.var1 ---- Hello@19e0bfd
h1.var2 ---- Hello@139a55
h1.var1 ---- Hello@19e0bfd
h1.var2 ---- Hello@19e0bfd
Assuming there is a class named Hello, How would I declare variables
named var1 and var2 to be references to objects in the class Hello? I
assumed it would just be Hello var1, var2;
You can see there are two variables declared of same class which can be reference to Hello
class instance.
Also to just construct an instance of the object of the class Hello
using the default constructor would it just be Hello hello = new
Hello();
Yes there is default constructor associated with each class so you can do initialize class like this.
Finally my last question is if I were to instantiate an object of the
class Hello using the default constructor and assign that object to
the varaible named var1 it would just be Hello var1 = new Hellow();.
How would I assign the reference to the object named var1 to the
variable named var2
As you see the output the hash code of var2
is same as var1
after h1.var2 = h1.var1
statement. This states that var2
previous reference is replaced by var1
reference. So here objects are not copied but references to objects are copied. Check the same hashcode
of var1
and var2
.
Thats it!.