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