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. Here I want to ensure that the key that is set for Bar is a specific subclass of FooKey (i.e. 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.
In order to do this, you need to make the superclass generic: