January 31, 2011

Polymorphism in Java

Write an Interface - name it MyInterface with a method declaration for m1()
Write a concrete class - name it Sup - make it implement MyInterface - m1() prints "In Super class".
Create a concrete subclass of this class - name it Sub - override m1() in Sub that prints "In Sub Class"

MyInterface i;
...
i.m1(); // this should print "In Super Class"
...
i.m1(); // this should print "In Sub Class"


Solution

MyInterface.java

interface MyInterface {
   public void m1();    
}

Sup.java

class Sup implements MyInterface {
   public void m1() {
      System.out.println("In Super Class");
   }
}

Sub.java

class Sub extends Sup {
   public void m1() {
      System.out.println("In Sub Class");
   }
}

Driver.java

public class Driver {
   public static void main(String[] args) {
      MyInterface i;
      i = new Sup();
      i.m1();             // prints "In Super Class"
      i = new Sub();
      i.m1();             // prints "In Sub Class"
   }
}

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;
   }
}