-1

I teach some students.
How I can access A class's attribute 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);
    }
}
ItamarG3
  • 4,092
  • 6
  • 31
  • 44

2 Answers2

0

It violates principles of object oriented design and is not possible in Java. There are some ugly workarounds, but if you're teaching students then it may be best to not even introduce this idea, or at least explain why it doesn't make sense.

This question is almost a duplicate if you really need a way of doing this: Why is super.super.method(); not allowed in Java?

nickburris
  • 11
  • 4
0

With Following code , you can achieve.

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);
    }
}
Hardeep Singh
  • 743
  • 1
  • 8
  • 18