Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何访问父项的年龄字段';谁的父母在C班?_Java_Inheritance_Extends - Fatal编程技术网

Java 如何访问父项的年龄字段';谁的父母在C班?

Java 如何访问父项的年龄字段';谁的父母在C班?,java,inheritance,extends,Java,Inheritance,Extends,我教一些学生。 如何访问类的属性年龄 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{

我教一些学生。
如何访问类的属性年龄

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);
    }
}

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


如果您真的需要一种方法来实现这一点,那么这个问题几乎是重复的:

使用以下代码,您可以实现

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);
    }
}

通过添加
受保护的整数
至于子类,我想你是在跟踪超变量
“我为教一些学生而工作。”
——??@HovercraftFullOfEels我在一则招聘英语教师的广告中看到了一个非常类似的句子。试着加入
public void showInfo()
即使在类B中,也可以打印
super.age
,然后在类中重写的方法中调用函数
super.showinfo()
C@HovercraftFullOfEels现在好多了?这不是一个好问题,但它解决了这个难题。谢谢尼克伯里斯。是的,我知道你已经提到了。我只是想知道它是否可以访问。