在名为“ 面向对象编程概念 ”的课程中,对面向对象概念的介绍以自行车类为例,其中赛车,山地自行车和双人自行车为子类。这是一个Bicycle类的可能实现的示例代码,以概述类的声明。本课程的后续部分将重复并逐步解释类声明。目前,不要担心细节。

    1. public class Bicycle {
    2. // the Bicycle class has
    3. // three fields
    4. public int cadence;
    5. public int gear;
    6. public int speed;
    7. // the Bicycle class has
    8. // one constructor
    9. public Bicycle(int startCadence, int startSpeed, int startGear) {
    10. gear = startGear;
    11. cadence = startCadence;
    12. speed = startSpeed;
    13. }
    14. // the Bicycle class has
    15. // four methods
    16. public void setCadence(int newValue) {
    17. cadence = newValue;
    18. }
    19. public void setGear(int newValue) {
    20. gear = newValue;
    21. }
    22. public void applyBrake(int decrement) {
    23. speed -= decrement;
    24. }
    25. public void speedUp(int increment) {
    26. speed += increment;
    27. }
    28. }

    Bicycle的一个子类,MountainBike类的类声明可能是这样:

    1. public class MountainBike extends Bicycle {
    2. // the MountainBike subclass has
    3. // one field
    4. public int seatHeight;
    5. // the MountainBike subclass has
    6. // one constructor
    7. public MountainBike(int startHeight, int startCadence,
    8. int startSpeed, int startGear) {
    9. super(startCadence, startSpeed, startGear);
    10. seatHeight = startHeight;
    11. }
    12. // the MountainBike subclass has
    13. // one method
    14. public void setHeight(int newValue) {
    15. seatHeight = newValue;
    16. }
    17. }

    MountainBike继承Bicycle的所有字段和方法,并添加字段seatHeight及其设置方法(山地自行车的座椅可以根据地形要求上下移动)。