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

No comments:

Post a Comment