【问题标题】:how can access the age field of parent's parent in class C?如何在 C 类中访问父母父母的年龄字段?
【发布时间】:2023-04-10 00:05:01
【问题描述】:

我教一些学生。
如何访问 A 类的属性 age?

class A {
    protected int age;
    public A(int age){
        this.age = age+2;
    }
}
class B extends A{
    protected int age;
    public B(int age){
        super(age);
        this.age = age+1;
    }
}
class C extends B{
    protected int age;
    public C(int age){
        super(age);
        this.age = age;
    }
    public void showInfo(){
//      System.out.println(A.this.age);
        System.out.println(super.age);
        System.out.println(this.age);
    }
}

【问题讨论】:

  • 通过将protected int age; 添加到子类中,我认为您正在隐藏超级变量
  • "I works for teaching some students." -- ??
  • @HovercraftFullOfEels 我在一个英语老师的广告中看到了一个非常相似的句子。
  • 尝试在 B 类中包含 public void showInfo() 并打印 super.age,然后在 C 类的重写方法中调用函数 super.showinfo()
  • @HovercraftFullOfEels 现在好点了吗?这不是一个好问题,但它消除了这个困难。

标签: java inheritance extends


【解决方案1】:

它违反了面向对象设计的原则,在 Java 中是不可能的。有一些丑陋的解决方法,但如果你正在教学生,那么最好不要引入这个想法,或者至少解释为什么它没有意义。

如果您真的需要这样做的方法,这个问题几乎是重复的:Why is super.super.method(); not allowed in Java?

【讨论】:

  • 感谢 nickburris。是的,我知道你已经提到过。我只是想知道它是否可以访问。
【解决方案2】:

通过以下代码,即可实现。

class A{
    protected int age;
    public A(int age){
        this.age = age+2;
    }

    public void showInfo()
    {
        System.out.println("A : " +  this.age);
    }
}
class B extends A{
    protected int age;
    public B(int age){
        super(age);
        this.age = age+1;
    }

    public void showInfo()
    {
        super.showInfo();
        System.out.println("B : " +  this.age);
    }
}
class C extends B{
    protected int age;
    public C(int age)
    {
        super(age);
        this.age = age;
    }
    public void showInfo()
    {
        super.showInfo();
        System.out.println("C : " +  this.age);
    }
}

【讨论】:

    猜你喜欢
    • 2018-07-15
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    相关资源
    最近更新 更多