简体   繁体   English

继承 - 重写mutator方法?

[英]Inheritance - overriding mutator methods?

So, let's say I have the following classes: 所以,假设我有以下课程:

Foo

abstract class Foo{
    .
    .
    .
    public void setKey(FooKey key){
        this.key = key;
    }
}

Bar 酒吧

final class Bar extends Foo{
    .
    .
    .
    @Override
    public void setKey(BarKey key){ // Can't do this?
        super.setKey(key);
    }
}

In the above example, BarKey is a subclass of FooKey . 在上述例子中, BarKey是的一个子类FooKey Here I want to ensure that the key that is set for Bar is a specific subclass of FooKey (ie BarKey ). 在这里,我想确保为Bar设置的键是FooKey的特定子类(即BarKey )。 How do I go about this? 我该怎么做? Am I making this overly complicated? 我是否过于复杂? Is there a better design approach? 有更好的设计方法吗?

This isn't correct, because you're making the subclass more restrictive than the superclass: the superclass makes it possible to set any kind of FooKey, but the subclass only accepts BarKey. 这是不正确的,因为你使子类比超类更具限制性:超类可以设置任何类型的FooKey,但子类只接受BarKey。

In order to do this, you need to make the superclass generic: 为此,您需要使超类具有通用性:

abstract class Foo<K extends FooKey> {
    private K key;

    public void setKey(K key){
        this.key = key;
    }
}

final class Bar extends Foo<BarKey> {
}

You can't enforce it that way. 你不能这样强制执行。 Consider: 考虑:

Bar b = new Bar();
FooKey k = new FooKey();
b.setKey(k);  // You want to prohibit this
Foo f = b;
f.setKey(k);  // But there's no way to prohibit this

In general, a derived class can't offer a more restrictive interface than its superclass. 通常,派生类不能提供比其超类严格的接口。

So I would suggest removing setKey from the abstract class. 所以我建议从抽象类中删除setKey

You should read about difference between overriding and overloading. 您应该阅读覆盖和重载之间的区别。 The thing you did is simply overloading because you change the argument type which is not allow with overriding. 你所做的只是简单重载,因为你改变了覆盖不允许的参数类型。

Simply remove the @Override annotation as you're not overriding the method of the super class, (should be same arguments), you're just defining a new setKey method with a narrower type. 简单地删除@Override注释,因为你没有覆盖超类的方法(应该是相同的参数),你只是定义一个具有更窄类型的新setKey方法。 This new setKey method will be accessible only through a Bar reference, however. 但是,这个新的setKey方法只能通过Bar引用访问。

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

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