- protected
继承有个特点,就是子类无法访问父类的private
字段或者private
方法。
这使得继承的作用被削弱了。为了让子类可以访问父类的字段,我们需要把private
改为protected
。
class Person {
protected String name;
protected int age;
}
class Student extends Person {
public String hello() {
return "Hello, " + name; // 这样就可以了
}
}
-super() --------------// 调用父类的构造方法
class Student extends Person {
protected int score;
public Student(String name, int age, int score) {
super(name, age); // 调用父类的构造方法Person(String, int)
this.score = score;
}
}