Logo
1 Jan 0001 | 1 min. (100 words)

子类重写父类的方法时返回类型和父类方法的返回类型可以不同,但是子类的返回类型必须是父类方法返回类型的子类。

父类

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();
    }

…

…

© 2009-2017 lastsweetop.com 版权所有 粤ICP备15102984号
Menu