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

有帮助吗?

解决方案

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

其他提示

You have a typo error(somFunction instead of someFunciton) in your class Test2 and you have not overridden the function instead you have new function somFunction.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top