How to find out if a method is overridden by child classes?
For example,
public class Test {
static public class B {
public String m() {return "From B";};
}
static public class B1 extends B {
}
static public class B2 extends B {
public String m() {return "from B2";};
}
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) {
B b1 = new B1();
System.out.println("b1 = " + b1.m());
B b2 = new B2();
System.out.println("b1 = " + b2.m());
}
}
Given an instance of B, how do I know if any derived classes have overridden method m() like B2?
Update: My question wasn't clear. Actually, I was trying to ask if this is possible without resorting to reflection. This check is done in a tight loop and it's used in a performance hack to save a few CPU cycles.
getMethod("myMethod"). getDeclaringClass(); If the class that's returned is your own, then it's not overridden; if it's something else, that subclass has overridden it.
Calling Parent class's overridden method from Child class's method using super keyword. from Derived class function will call base class version of display() function i.e.
Therefore, you cannot override two methods that exist in the same class, you can just overload them.
Overridden methods are not inherited.
This question helps demonstrate how to get the information of which class that method belongs to:
How to quickly determine if a method is overridden in Java
class.getMethod("myMethod").getDeclaringClass();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With