Bean_Man 2017-03-21 14:06 采纳率: 0%
浏览 3974

java中如何访问父类的父类的属性

子类能不能直接用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);
        }
    }
    

    参考:https://www.cnblogs.com/levi1994/p/5568433.html

    评论

报告相同问题?

悬赏问题

  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏