Number945
Number945

Reputation: 4940

Inheritance :hidden variable of superclass in subclass

Consider the following code :

class B
{
     int j=15;
}

public class A extends B
{
  int j=10;

  public static void main(String[] args)
  {
      A obj =new A();
      System.out.println(obj.j);   // i now want to print j of class B which is hidden,how?
  }

}

How should i reveal the hidden variable of a super class in subclass ?

Upvotes: 1

Views: 91

Answers (2)

enterbios
enterbios

Reputation: 1757

You can get to it from A class using super. You need to create a method for this. Example:

class A extends B
{
    int j=10;

    int getSuperJ() {
        return super.j;
    }

    public static void main(String[] args)
    {
        A obj =new A();
        System.out.println(obj.j);   //10
        System.out.println(obj.getSuperJ());  //15
    }

}

Upvotes: 0

Christian Tapia
Christian Tapia

Reputation: 34146

You can access to it, using super:

System.out.println(super.j);

but you can use super inside the class A, so you can do something like this:

public class A extends B
{
    int j = 10;

    public void print()
    {
        System.out.println(super.j);
    }

    public static void main(String[] args)
    {
        A obj = new A();
        System.out.println(obj.j); // 10
        obj.print(); // 15
    }
}

Upvotes: 4

Related Questions