0

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

4

2 回答 2

7

错字。

public void somFunction(){

应该

public void someFunction(){

正如 leonbloy 在评论中所说,如果您将注释 @Override 放在方法之前,编译器将在编译时检查它是否确实覆盖了某些东西。因此,如果它的方法名称是拼写错误(或者如果它覆盖的方法更改了签名),它将不会编译:

@Override public void somFunction(){ //compile time error
于 2013-05-06T01:19:05.003 回答
0

您的类 Test2 中有一个拼写错误(somFunction 而不是 someFunciton),并且您没有覆盖该函数,而是您有新的函数 somFunction。

于 2013-05-06T01:24:05.527 回答