创建类
声明类
java
public class Bicycle {
public int cadence;
public int gear;
public int speed;
public Bicycle(int startCadence, int startSpeed, int startGear) {
cadence = startCadence;
gear = startGear;
speed = startSpeed;
}
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;
}
}
java
public class MountainBike extends Bicycle {
public int seatHeight;
public MountainBike(int startHeight, int startCadence,
int startSpeed, int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}
public void setHeight(int newValue) {
seatHeight = newValue;
}
}
- 子类只能有一个父类
- 一个类可以实现多个接口
声明成员变量
- 类中的成员变量称为成员变量
- 方法或代码块中的变量称为局部变量
- 方法声明中的变量称为参数
java
public class Bicycle {
// 成员变量,称为字段
public int cadence;
public int gear;
public int speed;
// 方法声明中的变量,称为参数
public void setCadence(int newValue) {
// 局部变量
int temp;
// ...
}
}
私有字段
- 字段通常是私有的
- 可以通过方法访问字段
java
public class Bicycle {
private int cadence;
private int gear;
private int speed;
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
public int getCadence() {
return cadence;
}
public int getGear() {
return gear;
}
public int getSpeed() {
return speed;
}
}