定义车类Vehicle,小车类和自行车类Bicycle,注意父类和子类之间的关系。其中,Vehicle类的成员变量包括车轮数和载人数,成员方法包括停止方法,通过多态星,完成本程序。
2 回答
已采纳
frece
TA贡献36条经验 获得超15个赞
public class Test { public static void main(String[] args) { Vehicle vehicle = new Vehicle(); Vehicle car = new Car(); Vehicle bike = new Bicycle(); vehicle.stop(); car.stop(); bike.stop(); /** * 输出结果: * Vehicle Stop, numOfWheel: 0 maxPerson: 0 * Car Stop, numOfWheel: 4 maxPerson: 5 * Bicycle Stop, numOfWheel: 2 maxPerson: 2 * */ } } class Vehicle{ //车轮数 public int numOfWheel; //最大载人数 public int maxPerson; //停止方法 public void stop() { System.out.println("Vehicle Stop, numOfWheel: " + numOfWheel + " maxPerson: " + maxPerson); } } class Car extends Vehicle{ Car(){ //设置属性 this.numOfWheel = 4; this.maxPerson = 5; } @Override //重写停止方法 public void stop() { System.out.println("Car Stop, numOfWheel: " + numOfWheel + " maxPerson: " + maxPerson); } } class Bicycle extends Vehicle{ Bicycle(){ //设置属性 this.numOfWheel = 2; this.maxPerson = 2; } @Override //重写停止方法 public void stop() { System.out.println("Bicycle Stop, numOfWheel: " + numOfWheel + " maxPerson: " + maxPerson); } }
添加回答
举报
0/150
提交
取消