Saturday 28 September 2013

Method Call during Polymorphism

Simple interview question I faced:
    
                 There is a class Base which has a method meth() in its body. Also there is another class Derived which extends the Base class and overrides the meth() of Base class. Now if I create a Base class reference and assigns a derived class object, which method will be called when i give a call to meth() using Base class reference?

Eg:

public class OverrideMethodCallDemo {

public static void main(String[] args) {
Base b = new Derived();
b.meth();
}
}

class Base{
void meth(){
System.out.println("prints Base");
}
}

class Derived extends Base{
void meth(){
System.out.println(" prints Derived");
}
}

Result:

prints Derived.

No comments:

Post a Comment