有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用来自作为超类实例的对象上的子类的方法

假设有一个我广泛使用的类,它由一个方法返回

CommonClass obj = getCommonObject();

现在我想扩展这个类来创建一些实用方法,以避免重复我自己

public CommonClassPlus extends CommonClass {

    public String dontRepeatYourself() {
        // the reason I'm creating a subclass
    }
}

当然,我想用我改进的类来实现上面的方法,但是,向下投射是不允许的

CommonClassPlus obj = getCommonObject(); 
//Cannot cast to CommonClassPlus

如果只能处理作为超类实例的对象,如何使用方法dontRepeatYourself()

CommonClassgetCommonObject()来自外部库,我无法更改它们


共 (2) 个答案

  1. # 1 楼答案

    如果CommonClass来自外部库,您可能希望使用Composition over Inheritance的原理将其包装在Adapter Pattern

    如果您想(比如)更改正在使用的库,这将为您提供完全的控制,并允许您添加诸如dontRepeatYourself()之类的功能

    public class CommonClassAdapter implements MyAdapter {
        private final CommonClass common;
        private final String cachedResult;
    
        // Note that I'm doing dependency injection here
        public CommonClassAdapter(CommonClass common) {
            this.common = common;
    
            // Don't expose these because they shouldn't be called more than once
            common.methodIOnlyCallOnce();
            cachedResult = common.anotherMethodIOnlyCallOnce();
        }
    
        @Override
        public void someMethod() {
            common.someMethodWithDifferentName();
        }
    
        @Override
        public String dontRepeatYourself() {
            return cachedResult;
        }
    }
    

    还要注意的是,大多数现代IDE都有类似Eclipse的^{}这样的东西来加快这个过程

  2. # 2 楼答案

    您不能在Java中向现有实例添加行为(例如,您可以在JavaScript中这样做)

    Java中最接近的模式是装饰器模式:

    CommonClassPlus obj = decorate(getCommonObject());
    

    其中decorate()

    public CommonClassPlus decorate(CommonClass x) {
      return new CommonClassPlus(x);
    }
    

    这种方法可能会创建大量样板文件,因为它必须将每个方法调用委托给包装实例。如果CommonClass中的方法是final,并且没有可以重新实现的接口,那么这种方法将完全失败

    在大多数情况下,您将能够使用简单的静态助手方法:

    public static String dontRepeatYourself(CommonClass x) {
       ...
    }