1.访问修饰符
访问修饰符 | 本类 | 同包 | 子类 | 其他 |
private | √ | |||
默认(friendly) | √ | √ | ||
protected | √ | √ | √ | |
public | √ | √ | √ | √ |
2.方法重写
方法重写的规则:
在继承关系的子类中;重写的方法名、参数、返回值类型必须和父类相同;私有方法不能继承因而也无法重写
方法重写和方法重载
位置 | 方法名 | 参数表 | 返回值 | 访问修饰符 | |
方法重写 | 子类 | 相同 | 相同 | 相同 | 不能比父类更严格 |
方法重载 | 同类 | 相同 | 不同 | 无关 | 无关 |
方法重写的意义是实现多态
3.抽象类和抽象方法
利用abstract来定义抽象类;抽象类不能被实例化
public abstract class Instrument {
protected String brand;
protected int weight;
public Instrument(String brand, int weight) {
super();
this.brand = brand;
this.weight = weight;
}
}
abstract也可以用于方法----抽象方法
抽象方法没有实体;抽象方法必须在抽象类里面;抽象方法必须在子类中被实现,除非子类是抽象类
public abstract class Instrument {
protected String brand;
protected int weight;
public Instrument(String brand, int weight) {
super();
this.brand = brand;
this.weight = weight;
}
public abstract void play();//抽象方法
}