子类能不能直接用this.XX 访问父类的父类中的属性啊, 这个属性的权限是public
4条回答 默认 最新
- Upping 2019-04-19 19:21关注
需要强转一下,即: ((PersonOfPerson)this).xxx。
示例代码如下:class PerParent { public String color; public PerParent() { this.color = "white"; } public void printColor() { System.out.println(color); } } public class Parent extends PerParent{ public String color; public Parent(){ this.color="green"; } public void printColor(){ System.out.println(color); } public static void main(String args[]){ System.out.println(((PerParent) new Child()).color); System.out.println(((Parent) new Child()).color); System.out.println(new Child().color); new Child().printColor(); new Child().printSuperColor(); new Child().printSuperSuperColor(); } } class Child extends Parent{ public String color; public Child(){ color="black"; } public void printColor(){ System.out.println(color); } public void printSuperColor(){ System.out.println(super.color); System.out.println(((Parent)this).color); } public void printSuperSuperColor(){ System.out.println(((PerParent)this).color); } }
解决 2无用