转载

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();
    }
原文  https://blog.csdn.net/lastsweetop/article/details/82658312
正文到此结束
Loading...