java遺珠之協變返回型別
版權宣告:本文為博主原創文章,未經博主允許不得轉載。https://blog.csdn.net/lastsweetop/article/details/82658312
子類重寫父類的方法時返回型別和父類方法的返回型別可以不同,但是子類的返回型別必須是父類方法返回型別的子類。
父類
public class Bicycle { private int cadence; private int gear; private int speed; public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; } public Bicycle newBike() { return new Bicycle(1, 1, 1); } }
子類
public class MountainBike extends Bicycle { public int seatHeight; public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) { super(startCadence, startSpeed, startGear); seatHeight = startHeight; } @Override public MountainBike newBike() { return new MountainBike(1, 1, 1, 1); } }
如果返回型別不是父類返回型別的子類就會報錯:attempting to use incompatible return type
@Override public Object newBike() { return new Object(); }