1

How to get information about child classes overridden methods information in the abstract parent class. Example:

abstract Class A()
{
  protected void a1()
  {
    //some default content
  }
  protected void a2()
  {
    //some default content 
  }
}

 class B extends A
 {
    @Override
     public void a1()
      {
         //overridden content
      }
 } 
Class C extends A
{
   @Override
   public void a2()
   {
     //overriden content
   }
}

How get the information that Class c is overriding only a2 and Class B is overriding a1

  • I don't understand your question. Do you mean how to check if the method has been overridden? – user3437460 Oct 11 '17 at 03:27
  • Some extra concrete details would help understand the problem you're having. In general, in a good design `A` should *always* assume that its subclasses have valid implementations of all of its methods. That's the point of the contract! If `a1` is only applicable to some of `A`'s subclasses, it's likely that the logic using `a1` should be pushed to the subclass that needs it. – Mark Peters Oct 11 '17 at 03:27

1 Answers1

1

You can do following to play around (through refelction):

java.lang.Class class = B.class; // or any other child class
Class dec = class.getMethod("YourMEthodNAme").getDeclaringClass();
System.out.println(" Declaring class: " + dec.toString());

// you can check the anme of returned class, if it's A for a given method, then method is not overridden, if it's child class name , it's overriden

EDIT:

You can also do this in a loop:

      Method[] m = class.getMethods();
      for(int i = 0; i < m.length; i++) {

         // returns te declaring class
         Class dec = m[i].getDeclaringClass();

         // displays all methods
         System.out.println("Method = " + m[i].toString());
         System.out.println(" Declaring class: " + dec.toString());
      }
tryingToLearn
  • 10,691
  • 12
  • 80
  • 114