How to implement only certain methods of an abstract class?

无人久伴 提交于 2019-12-23 02:49:05

问题


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?


回答1:


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.




回答2:


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.




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!