January 31, 2011

Java Object Reference Variables

Write a Java class - name it Test - with one instance variable of type int and another instance variable of type Test.
Write an instance method - name it method1().
In method1(), create an instance of Test, referred to by t1.
Make the instance variable of type Test of the object referred to by t1 refer to another new instance.
Create another reference variable of Test, t2. Do not refer t2 to a new instance.
Make t2 refer to the object referred to by t1's Test instance variable.

Solution

Test.java

class Test {
   
   int i;
   Test t;

   void method1() {
      Test t1 = new Test();
      t1.t = new Test();
      Test t2;
      t2 = t1.t;
   }
}

2 comments:

  1. How will this program run without a main method?????

    ReplyDelete
  2. It won't run without a main method. It will just compile. The objective is to understand the concept of object reference variables and the terminology.

    ReplyDelete