I am trying to get my head around Dynamic method invoking in java and not able to understand why java does not let me invoke method from subclass instead of method of superclass.
For example:
If I have 2 classes Test
and Test2
. Test2 inherits from class Test
The method someFunction()
is overridden in the subclass:
Test class
public class Test {
public Test(){
System.out.println("I am Test class constructor called with no values");
}
public void someFunction(){
System.out.println("I am some function belonging to Test Class");
}
}
And Test2 class:
public class Test2 extends Test{
public Test2(){
System.out.println("Constructor of Test2 with no values");
}
public void somFunction(){
System.out.println("I am someFunction overridden in Test2");
}
}
So when I try to instantiate the Test class in this way:
Test t1 = new Test2();
t1.someFunction(); // this should call Test2.someFunction()
The output I get is:
I am Test class constructor called with no values
Constructor of Test2 with no values
I am some function belonging to Test Class
So my question is:
When I call the method someFunction()
using object t1
why does it invoke the method belong to the superclass instead the one in subclass even when I am initializing the object with subclass.
I always thought that dynamic invoking used to work in this way that the class you initialize the object with, the methods of that class are called i.e basically overridden method should be called instead of the parent method.
Dinesh