Manikandan Kbk DIP
Manikandan Kbk DIP

Reputation: 483

How to find which class has overridden a function in a complex inheritance hierarchy?

In case of a complex inheritance hierarchy like down the line,

A has a function name whoOverrideMeLatest();

A {Interface}
|
B {Interface}
|
C {abstract class} {implemented whoOverrideMeLatest()}
|
D {abstract class extending C and implementing some random 5 interfaces} {overrides whoOverrideMeLatest()}
|
E {concrete class}
|
F {concrete class}
|
G {G is abstract class which extends F and implements 10 other interfaces}
|
H {concrete class and overrides whoOverrideMeLatest()}
|
I {abstract class extending H and implementing 3 interfaces}
|
J {concrete class}

Suppose If I create instance of J in the following manner,

A a = new J();

As you can see the last override of the function whoOverrideMeLatest() happened in class "H". Given there is too much of class, abstract class and interface implementation happening at each level, you can understand the complexity and volume of method overloading and the amount of functions each class carry. Doing it manually and finding out is always hard :(

Question,

  1. Is there anything in Java, given an object and a function as input and that tells me which class has overridden the function last in the hierarchy.

For example,

For => A a = new J(); I need to get class "H" as output

For => A a = new F(); I need to get class "D" as output

Upvotes: 0

Views: 35

Answers (2)

Manikandan Kbk DIP
Manikandan Kbk DIP

Reputation: 483

Found a better way to do it,

Found a better way to do it,

A a= new J();
Method[] methods = a.getClass().getMethods();
for(Method method : methods) {
    System.out.println(method.getDeclaringClass() + " " + method.getName());
}

method.getDeclaringClass() returns the latest overridden class name.

Upvotes: 1

shalama
shalama

Reputation: 1335

You can just call whoOverrideMeLatest on object of A. It will call the function thats is last in the hierarchy. Thats called polymorphism. Ofcourse you have to implement whoOverrideMeLatest in all concret classes that should implement whoOverrideMeLatest.

    class E extends D{
     whoOverrideMeLatest (){
     System.out.println("E");
    }
   } 

Upvotes: 0

Related Questions