为什么我不能扩展接口"generic method"并将其类型缩小到我继承的接口"class generic"?



我举一个例子来说明我的意思,哪个更容易。想象一下,通用类型 C 表示颜色类型:所以对于视觉简化假设 C 是 C 扩展颜色

interface Screen {
   <C> Background<C> render(Plane<C> plane);
}
interface MonochromeScreen<C> extends Screen{
       @Override
       Background<C> render(Plane<C> plane);  
}

这将引发名称冲突编译错误,说明两者具有相同的类型擦除,但不可覆盖。

但我不明白为什么我们不能简单地允许覆盖签名,只要它更具限制性。我的意思是,毕竟,唯一的区别是泛型类型的范围,在 Screen 中是方法范围的,而在 MonochromeScreen 中是类范围的。

当子方法的父

方法在类级别强制执行一致性时,允许子方法覆盖为方法范围的泛型是没有意义的,但我认为它不会这样做:我的父接口可能有 20 个具有不相关泛型类型的方法,但我的子类会强制它们都与不兼容的额外规范/合约相同(这是任何扩展接口所做的(, 毕竟,单色的 sccreen 仍然是一个屏幕,因为它可以用任何颜色涂上,我只是强制执行这种颜色,无论它是什么,让它在孩子的其他功能中保持一致,只是缩小了班级级别的可能性,而不是方法级别。

考虑该功能是否有任何根本错误的假设?

编辑:我接受了Sotirios Delimanolis的回答,因为他非常聪明地发现了正确的问题,我不是在要求解决方案,但是对于那些想知道如何克服这种情况的人来说,在我自己的回答中解释了一个技巧

这是中断的地方:

MonochromeScreen<Red> redScreen = ...;
Screen redScreenJustAScreen = redScreen;
Plane<Blue> bluePlane = null;
redScreenJustAScreen.<Blue>render(bluePlane);

如果您建议的内容在编译时有效,则上面的代码片段可能必须在运行时失败并出现ClassCastException,因为redScreenJustAScreen引用的对象需要Plane<Red>但收到Plane<Blue>

如果使用

得当,泛型应该可以防止上述情况发生。如果允许此类覆盖规则,泛型将失败。

我对你的用例不够了解,但似乎并不真正需要泛型。

不允许这样做的原因是它违反了利斯科夫替换原则。

interface Screen {
   <C> Background<C> render(Plane<C> plane);
}

这意味着您可以随时使用任意类型调用render(),如 C

例如,您可以执行此操作:

Screen s = ...;
Background<Red> b1 = s.render(new Plane<Red>());
Background<Blue> b2 = s.render(new Plane<Blue>());

现在,如果我们看MonochromeScreen

interface MonochromeScreen<C> extends Screen{
   Background<C> render(Plane<C> plane);  
}

声明所说的是:创建此对象的实例时,必须C只选择一种类型,并且只能在该对象的整个生命周期内使用该类型。

MonochromeScreen<Red> s = ...;
Background<Red>  b1 = s.render(new Plane<Red>());
Background<Blue> b2 = s.render(new Plane<Blue>()); // this won't compile because you declared that s only works with Red type.

因此,Screen s = new MonochromeScreen<Red>();不是有效的强制转换,MonochromeScreen不能是Screen的子类。


好吧,让我们稍微扭转一下。假设所有颜色都是单个Color类的实例,而不是单独的类。那么我们的代码会是什么样子呢?

interface Plane {
    Color getColor();
}
interface Background {
    Color getColor();
}
interface Screen {
   Background render(Plane plane);
}

目前为止,一切都好。现在我们定义一个单色屏幕:

class MonochromeScreen implements Screen {
    private final Color color; // this is the only colour we have
    public Background render(Plane plane) {
        if (!plane.getColor().equals(color))
           throw new IllegalArgumentException( "I can't render this colour.");
        return new Background() {...}; 
    }
}

这将编译得很好,并且或多或少具有相同的语义。

问题是:这会是好的代码吗?毕竟,您仍然可以这样做:

public void renderPrimaryPlanes(Screen s) { //this looks like a good method
    s.render(new Plane(Color.RED));
    s.render(new Plane(Color.GREEN));
    s.render(new Plane(Color.BLUE));
}
...
Screen s = new MonochromeScreen(Color.RED);
renderPrimaryPlanes(s); //this would throw an IAE

嗯,没有。这绝对不是您对无辜renderPrimaryPlanes()方法的期望。事情会以意想不到的方式破裂。为什么?

这是因为尽管它在形式上有效且可编译,但此代码也以与原始代码完全相同的方式破坏了 LSP。问题不在于语言,而在于模型:你调用的实体Screen可以做比称为MonochromeScreen的实体更多的事情,因此它不能是它的超类。

仅供参考:这是我发现解决案例并通过方法覆盖的唯一方法(如果设计模式有名称,我希望知道 ir!最终,这是使用泛型方法扩展接口以使其成为类泛型的方式。您仍然可以使用父类型(又名 Color(键入它,以将其用作原始通用类型的旧界面。

屏幕.java

public interface Screen {
    public interface Color {}
    public class Red  implements Color {}
    public class Blue implements Color {}
    static Screen getScreen(){
        return new Screen(){};
    }
    default <C extends Color> Background<C> render(Plane<C> plane){
        return new Background<C>(plane.getColor());
    }
}

单色屏幕.java

interface MonochromeScreen<C extends Color> extends Screen{
    static <C extends Color> MonochromeScreen<C> getScreen(final Class<C> colorClass){
        return new MonochromeScreen<C>(){
            @Override public Class<C> getColor() { return colorClass; };
        };
    }
    public Class<C> getColor();
    @Override
    @SuppressWarnings("unchecked")
    default Background<C> render(@SuppressWarnings("rawtypes") Plane plane){
        try{
            C planeColor = (C) this.getColor().cast(plane.getColor());
            return new Background<C>(planeColor);
        } catch (ClassCastException e){
            throw new UnsupportedOperationException("Current screen implementation is based in mono color '" 
                                                   + this.getColor().getSimpleName() + "' but was asked to render a '"
                                                   + plane.getColor().getClass().getSimpleName() + "' colored plane" );
        }
    }
}

飞机.java

public class Plane<C extends Color> {   
    private final C color;
    public Plane(C color) {this.color = color;}
    public C getColor()   {return this.color;}
}

背景.java

public class Background<C extends Color> {  
    private final C color;
    public Background(C color) {this.color = color;}
    public C getColor()        {return this.color;}
}

主测试.java

public class MainTest<C> {
    public static void main(String[] args) {
        Plane<Red> redPlane   = new Plane<>(new Red());
        Plane<Blue> bluePlane = new Plane<>(new Blue());
        Screen coloredScreen = Screen.getScreen();
        MonochromeScreen<Red> redMonoScreen = MonochromeScreen.getScreen(Red.class);
        MonochromeScreen<Color> xMonoScreen = MonochromeScreen.getScreen(Color.class);
        Screen redScreenAsScreen = (Screen) redMonoScreen;
        coloredScreen.render(redPlane);
        coloredScreen.render(bluePlane);
        redMonoScreen.render(redPlane);
        //redMonoScreen.render(bluePlane); --> This throws UnsupportedOperationException*
        redScreenAsScreen.render(redPlane);
        //redScreenAsScreen.render(bluePlane); --> This throws UnsupportedOperationException*
        xMonoScreen.render(new Plane<>(new Color(){})); //--> And still I can define a Monochrome screen as of type Color so  
        System.out.println("Test Finished!");           //still would have a wildcard to make it work as a raw screen (not useful 
                                                        //in my physical model but it is in other abstract models where this problem arises
    } 
}
  • 在红屏中添加蓝色平面时引发异常:

    java.lang.UnsupportedOperationException: Current screen 实现 基于单色"红色",但被要求渲染"蓝色"颜色 飞机

我不认为你的代码是你想要的,这就是你收到错误的原因。

我认为这就是你想要的

public interface Screen<C> {
    Background<C> render(Plane<C> plane);
}

public interface MonochromeScreen<C> extends Screen<C> {
  Background<C> render(Plane<C> plane);
}

您可能会误以为<C>因为两个接口,所以它是同一件事。不是。

public interface MonochromeScreen<HI> extends Screen<HI> {
  Background<HI> render(Plane<HI> plane);
}

与上面的代码完全相同。C 和 HI 只是泛型占位符的名称。通过使用extends Screen<HI>扩展Screen<C>,我们告诉JavaC与HI是相同的placeHolder,因此它将发挥其魔力。

在您的代码中

<C> Background<C> render(Plane<C> plane);

我们声明了一个全新的占位符,该方法中只有上下文。所以我们可以编写这段代码

MonochromeScreen<String> ms;
ms.render(new Plane<Banana>());
<C> Background<C> render(Plane<C> plane);

被重新定义为

Background<Banana> render(Plane<Banana> plane);

Background<C> render(Plane<C> plane);

被重新定义为

Background<String> render(Plane<String> plane);

哪个冲突,所以Java给你一个错误。

最新更新