Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why overridden method calling from Subclass if i have done up-casting?

i have just started learning java::Inheritance and confused while mixing Up-Casting.

class Example{
     public void methodOne(){
        System.out.println("Example::Method_1");
     }

     public void methodTwo(){
        System.out.println("Example::Method_2");
     }
}

public class Test extends Example{

     public void methodTwo(){                  //Method overriding
        System.out.println("Test::Method_2");
     }

     public void methodThree(){
        System.out.println("Test::Method_3");
     }

    public static void main(String[] args){

        Example exa = new Test();             // UpCasting

        exa.methodOne();                      // Printing Example::Method_1
        exa.methodTwo();                      // Printing Test::Method_2
        // exa.methodThree();                 // Error : can not find symbol
 }
}

may someone please explain, what happening here??

like image 841
Avinash Kumar Avatar asked Aug 13 '17 12:08

Avinash Kumar


1 Answers

When using inheritance, the compile-time type of the reference to an object on which you call a method is only used to see (at compile time) if the method may be invoked.

But at the invocation time, it does not matter what that compile-time type is. What really matters in this case is the runtime type of the object. It is Test, so the method is searched on Test first.

For methodOne() it is a bit different: it is not overriden by Test, so the version from its superclass (Example) is invoked.

like image 167
Roman Puchkovskiy Avatar answered Sep 24 '22 12:09

Roman Puchkovskiy