简体   繁体   中英

How to find out the proper overridden method in Eclipse

I have one interface I1 which defines a method M1 . Two other classes C1 and C2 are implementing I1 and over-rides M1 .

In another class C3 I have a reference to M1 . Now how will I understand if M1 is referring to C1_M1 or C2_M1 ?

PS I can find it out while debugging the code. But I am looking for some shortcut without executing it.

It is run time polymorphism so you are able to understand it at run time only.

If you know what will be the input to your program then you can understand which class instance reference came.

interface A{

}

class B implements A{

}

class C implements A{

}

class Main{

  public static void main(String args[]){

    // input
    Object o = new B();  // just assume your logic give you object B. 

    if(o instanceof B){
       B b = (B) o;
     // invoke methods 
    }else if(o instanceof C){
      C c = (C) o;
     // invoke methods
    }
  }

}

In above code you are able to understand that class B methods will be invoked.

Summary of all is - you have to understand your code, recognize the inputs and then you are able to understand which class will be called at run time. otherwise debugging is best practice.

if you created object in this way

I1 i=new c1();

then i.m1() will call m1 method of class c1

if

  I1 i=new c2();

then i.m1() will call m1 method of class c2

If you don't know how the object is created and you have only the reference then Sorry to Say you can only find it at runtime as it is Run time Polymorphism

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM