Classes
在标题为面向对象的编程概念的类中,有关面向对象概念的介绍以自行车类为例,其中赛车,山地车和 Double 人自行车是子类。以下是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;
}
}
MountainBike
类的Bicycle
子类的类声明可能看起来像这样:
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
字段和一种设置方法(山地自行车的座椅可以根据地形要求上下移动)。