继承后成员的访问特点
父类的构造方法不能被继承
父类的私有成员
父类的私有成员可以被子类继承,但子类不能直接访问,需要借助父类的公有方法
class Father {
private String fatherName;
public Father() {
}
public Father(String fatherName) {
this.fatherName = fatherName;
}
public String getFatherName() {
return fatherName;
}
public void setFatherName(String fatherName) {
this.fatherName = fatherName;
}
private void printFatherName() {
System.out.println("father name: " + fatherName);
}
public void publicMethod() {
printFatherName();
}
}
class Son extends Father{
public void sonMethod() {
/**
* 2. 私有变量或私有方法
* 1. 子类可以继承父类的私有变量,但不能直接访问,需要使用父类的 setter/getter
*/
// System.out.println(fatherName); // 会编译异常
String fatherName = getFatherName(); // 可以拿到 fatername
System.out.println(fatherName);
// printFatherName(); // 编译异常
publicMethod(); // 可以正常打印 father name: xxx
}
}
父类的公有变量
子类可以继承父类的公有变量并直接访问
this 和 super
this
- 访问本类的构造方法,根据实参推定访问的是哪一个
- 访问本类的成员
注意
3. this()
只能在构造函数内第一行被使用
class Father {
private String name;
public Father() {
System.out.println("无参构造");
}
public Father(String name) {
// 访问构造函数,创建时会打印 "无参构造"
this();
this.name = name;
// this(); // this() 必须被放在第一行,编译异常
}
public String getName() {
// this(); // this(), 只能在构造方法内被使用,编译异常
return name;
}
public void setName(String name) {
// this.成员:用来访问本类的成员
this.name = name;
}
private void cook() {
System.out.println("father is cooking...");
}
public void print() {
// this.成员:用来访问本类的成员
this.cook();
}
}
super
super()
:访问父类的构造方法- 访问父类的公有成员
注意
3. super()
必须在构造方法的第一行(也就是 this
和 super
无法在同一个 constructor 中调用)
4. 子类的构造方法会默认调用 super()
,如果此时父类没有无参构造方法,那么会编译异常
class Son extends Father{
public Son() {
super();
System.out.println("son 无参构造");
// super(); // 编译异常:必须在第一行
}
public void sonMethod() {
// super(); // 编译异常:必须在 constructor 内调用
// super.name; //编译异常: private 访问不了
String fatherName = super.getName(); //
}
}