Dynamic Method Lookup in Java

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 ie basically overridden method should be called instead of the parent method.

Dinesh


Typo.

public void somFunction(){

should be

public void someFunction(){

As leonbloy says in the comments, if you place the annotation @Override before a method, the compiler will compile-time check that it actually overrides something. So if its method name is a typo (or if the method it overrides changes signature) it will not compile:

@Override public void somFunction(){ //compile time error

您的类Test2中有错字错误(somFunction而不是someFunciton),并且您没有重写该函数,而是使用了新函数somFunction。

链接地址: http://www.djcxy.com/p/78802.html

上一篇: Java中的静态变量

下一篇: Java中的动态方法查找