How to ensure that certain methods are called in an abstract superclass from a method in a subclass (Java)

I have an abstract superclass A with the doSomething() method. A subclass of class A must implement doSomething() , but there is also some generic code that must be called every time the subclass calls doSomething() . I know this can be achieved this way:

 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 problems with this:

  • Method signatures must match, but I may want to return something only in the methods of the subclass, but not in the superclass
  • If I do an abstraction of A.doSomething (), I cannot provide a (general) implementation in A. If I do not make it abstract, I cannot force the subclass to execute it.
  • If I use a different method to provide general functionality, I cannot ensure that calling B.doSomething () calls the general method.

Any ideas on how to apply the methods?

+6
source share
3 answers

add doSomething () callback

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

therefore, all subclasses will have ipmelment doSomethingMore () with additional actions, but external classes will call public doSomething ()

0
source

What about the next one?

 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 ... } } 

However, the first bullet is not so clear. The signature cannot match if you want to return something else.

+6
source

Only for the first item - you can consider the answer below and to implement the implementation of the subclass it can be abstract, but the call to the general functionality of the code can occur if the base class has some implementation.

The return type can be an object in the base class and return null. In SubClass, a specific return type can be specified below.

 public class InheritanceTutorial { static class Base{ public Object doSomething(){ System.out.println("parent dosomething"); return null; } } static class SubClass extends Base{ public Integer doSomething(){ super.doSomething(); System.out.println("child dosomething"); return 0; } } /** * @param args */ public static void main(String[] args) { SubClass subClass = new SubClass(); subClass.doSomething(); } } 
0
source

All Articles