如何只实现抽象类的某些方法? [英] How to implement only certain methods of an abstract class?

查看:201
本文介绍了如何只实现抽象类的某些方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的具体类中,我需要实现(设置公共)抽象类的某些方法。所以我无法扩展它,因为所有的抽象方法都是公开的。

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?

例如:

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(){ ...}
    }
}

有更好的方法吗?

推荐答案

抽象类的具体子类必须至少提供抽象方法的最小实现。

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


  • 可以实现你不想实现的方法来抛出未经检查的异常。 UnsupportedOperationException 是不错的选择,或者您可以使用更具体的含义来实现自己的类。

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

您可以将子类声明为 abstract ...但这意味着您将无法实例化它。

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.

这篇关于如何只实现抽象类的某些方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆