# 类

> 原文： [https://docs.oracle.com/javase/tutorial/java/javaOO/classes.html](https://docs.oracle.com/javase/tutorial/java/javaOO/classes.html)

在题为[面向对象编程概念](../../java/concepts/index.html)的课程中，面向对象概念的介绍使用自行车课程作为例子，赛车，山地自行车和双人自行车作为子类。下面是可能实现`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`和设置它的方法（山地自行车有座位，可以根据地形要求上下移动）。