Frage

In my concrete class I need to implement (set public) only certain methods of an abstract class. So I cannot extend it beacause all the abstract methods are public.

I could use composition, and forward just methods I need, but I obviously need to implement the abstract class. So, I'm wondering, is it a good approach to implement an abstract class in a private class and then forward in the parent class only the needed methods of the inner class?

For example:

public class ConcreteClass{

    private InnerClass inner = new InnerClass();

    public String fwMethod() {
        return inner.method1();
    }

    private class InnerClass extends AbstractClass {
        public String method1(){ ...}
        public String method2(){ ...}
    }
}

Is there some better approach?

War es hilfreich?

Lösung

A concrete subclass of an abstract class must provide at least minimal implementations of the abstract methods.

  • You could implement the methods that you don't want to implement to throw an unchecked exception. The UnsupportedOperationException (javadoc) is good choice, or you could implement your own exception class with a more specific meaning.

  • You could declare the subclass as abstract ... though that means you won't be able instantiate it.

  • You could refactor your base classes and interfaces so that your concrete class has fewer abstract methods to implement.

Andere Tipps

Why don't you modify the abstract class to inherit from another class, and you implements only the one with the methods you need ?

Example if you need only aa, ab instead of aa, ab, aaa, aab: class A, methods aa, ab class B, methods aaa, aab B inherits from A.

Your concrete class inherits from A and has access only to aa and ab, avoinding implements of aaa, aab.

Fully implement the methods that you need, and throw an UnsupportedOperationException in any method you don't want to implement.

See the javadoc for the exception's description.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top