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?
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
is good choice, or you could implement your own 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.
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.
Implement the methods you need, and throw an UnsopportedOperationException on any method you don't want to implement.
http://docs.oracle.com/javase/7/docs/api/java/lang/UnsupportedOperationException.html
来源:https://stackoverflow.com/questions/21699898/how-to-implement-only-certain-methods-of-an-abstract-class