在名为“ 面向对象编程概念 ”的课程中,对面向对象概念的介绍以自行车类为例,其中赛车,山地自行车和双人自行车为子类。这是一个Bicycle
类的可能实现的示例代码,以概述类的声明。本课程的后续部分将重复并逐步解释类声明。目前,不要担心细节。
public class Bicycle {
// the Bicycle class has
// three fields
public int cadence;
public int gear;
public int speed;
// the Bicycle class has
// one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
// the Bicycle class has
// four methods
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
}
Bicycle
的一个子类,MountainBike
类的类声明可能是这样:
public class MountainBike extends Bicycle {
// the MountainBike subclass has
// one field
public int seatHeight;
// the MountainBike subclass has
// one constructor
public MountainBike(int startHeight, int startCadence,
int startSpeed, int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}
// the MountainBike subclass has
// one method
public void setHeight(int newValue) {
seatHeight = newValue;
}
}
MountainBike
继承Bicycle
的所有字段和方法,并添加字段seatHeight
及其设置方法(山地自行车的座椅可以根据地形要求上下移动)。