Tuesday, 25 January 2011

Polymorphism Teaser

What would the output be from this piece of code?
/**
 * This represents any old super class with a print function
 **/
class SuperClass { 
    private void printIt()  {
        System.out.println("SuperClass");
    } 

    void printIt(boolean f) { 
        if (f)
        { 
            System.out.println("Super-part 2"); 
        } 
        else 
        { 
            printIt(); 
        } 
    } 
} 

/**
 * This is the sub class that ovcerrides one function
 **/
class SubClass extends SuperClass { 
    @Override
    void printIt() {
        System.out.println("SubClass");
    } 
} 

/**
 * This is a test class that gives some output
 **/
public class TestSub { 
    static void main(String args[]) { 
        SubClass sc=new SubClass(); // create the class
        sc.printIt();      // first print call
        sc.printIt(false); // second print call
    } 
} 

Answer

The output would be:
SubClass
SuperClass

This is because the second print call is in the context of the SuperClass and does not polymorphically jump back and call the sub class printIt.

No comments: