Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure a certain methods gets called in abstract super-class from method in sub-class (Java)

I have an abstract super class A with a method doSomething(). A sub-class of A must implement doSomething(), but there is also some common code that should be called every time a subclass calls doSomething(). I know this could be achieved thus:

public class A {
  public void doSomething() {
    // Things that every sub-class should do 
  }
}

public class B extends A {
  public void doSomething() {
    super.doSomething();
    // Doing class-B-specific stuff here
    ...
  }
}

There seem to be three issues with this, though:

  • The method signatures have to match, but I might want to return something in the sub-class methods only, but not in the super-class
  • If I make A.doSomething() abstract, I can't provide a (common) implementation in A. If I don't make it abstract, I can't force sub-class to implement it.
  • If I use a different method to provide the common functionality, I can't enforce that B.doSomething() calls that common method.

Any ideas how the methods should be implemented?

like image 515
martin_wun Avatar asked Aug 09 '15 13:08

martin_wun


People also ask

Can I access the sub class methods using a super class object?

Yes, you can call the methods of the superclass from static methods of the subclass (using the object of subclass or the object of the superclass).

How do you call a method of superclass from subclass?

Subclass methods can call superclass methods if both methods have the same name. From the subclass, reference the method name and superclass name with the @ symbol.

Does subclass inherit all methods of superclass?

Rule:A subclass inherits all of the member variables within its superclass that are accessible to that subclass (unless the member variable is hidden by the subclass). inherit those member variables declared with no access specifier as long as the subclass is in the same package as the superclass.


2 Answers

What about the following?

public abstract class A {
  protected abstract void __doSomething();

  public void doSomething() {
    // Things that every sub-class should do 
    __doSomething();
  }
}

public class B extends A {
  protected void __doSomething() {
    // Doing class-B-specific stuff here
    ...
  }
}

The first bullet point however is not so clear. The signature can't match if you want to return something different.

like image 141
MasterCassim Avatar answered Oct 21 '22 05:10

MasterCassim


add call back to doSomething()

public class A {
  public void doSomething() {
    // Things that every sub-class should do 
    doSomethingMore()
  }
}

protected abstract void doSomethingMore()

so all subclusses will have to ipmelment doSomethingMore() with additional actions but external classes will call public doSomething()

like image 35
kachanov Avatar answered Oct 21 '22 05:10

kachanov