文档

Java™ 教程-Java Tutorials 中文版
Trail: Learning the Java Language
Lesson: Classes and Objects

在标题为 Object-oriented Programming Concepts 的课程中,面向对象概念的介绍以自行车课为例,以自行车,山地自行车和串联自行车作为子类。以下是可能实现 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 以及设置它的方法(山地自行车有可移动的座位根据地形要求上下)。


Previous page: Classes and Objects
Next page: Declaring Classes