简体   繁体   English

如何仅实现抽象类的某些方法?

[英]How to implement only certain methods of an abstract class?

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 ( javadoc ) is good choice, or you could implement your own exception class with a more specific meaning. UnsupportedOperationException ( javadoc ) 是不错的选择,或者您可以实现自己的具有更具体含义的异常类。

  • You could declare the subclass as abstract ... though that means you won't be able instantiate it.可以将子类声明为abstract类……尽管这意味着您将无法实例化它。

  • 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.例如,如果您只需要 aa、ab 而不是 aa、ab、aaa、aab:类 A、方法 aa、ab 类 B、方法 aaa、aab B 继承自 A。

Your concrete class inherits from A and has access only to aa and ab, avoinding implements of aaa, aab.您的具体类继承自 A,并且只能访问 aa 和 ab,避免了 aaa、aab 的实现。

Fully implement the methods that you need, and throw an UnsupportedOperationException in any method you don't want to implement.完全实现您需要的方法,并在您不想实现的任何方法中抛出UnsupportedOperationException

See the javadoc for the exception's description.有关异常的描述,请参阅javadoc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM