Consider the example below.
Why is it so that I’m not allowed to use BImpl as a parameter type of method doSomething3? When I say “not allowed to”, I mean that Eclipse is complaining that the doSomething3-method from the interface AInf is not implemented.
interface AInf
{
AInf doSomething();
BInf doSomething2();
void doSomething3(BInf param);
}
interface BInf
{
}
class AImpl implements AInf
{
@Override
public AImpl doSomething() {
// TODO Auto-generated method stub
return null;
}
@Override
public BImpl doSomething2() {
// TODO Auto-generated method stub
return null;
}
@Override
public void doSomething3(BImpl param) // This method is not overriding the doSomething3(BInf param) from the AInf
{
// TODO Auto-generated method stub
}
}
class BImpl implements BInf
{
}
Because
doSomething3(BImpl param)doesn’t implementdoSomething3(BInf param).BInfcan have many implementations, and the method should work for all of them, not just one.Always bear in mind that extending a class or implementing an interface defines an
is arelationship. All the rules of widening/narrowing are logical consequences of this.It’s easier if you imagine it with a specific example: money. Coins are money and notes are money too.
If you go to a shop which decided to restrict the change they give you from your purchase to coins, it may be annoying but it’s legal. It’s fine because it doesn’t break the contract, they are always returning money.
But when you’re in a shop where they’re supposed to accept money and they won’t accept your coins, that’s not okay.