0

Consider the following code:

import java.io.*;
class a
{
    public int var1;
}
class b extends a
{
    public int var1;
}
class test 
{
    public static void main (String[] args) 
    {
        b obj = new b();
        System.out.println(obj.var1); // This should work!
        System.out.println(obj.a.var1); // This doesn't seem to work!
        // Is there any way to access the var1 inherited from a?
        
    }
}

Is there any way through which we can access the member variables or the member functions of the parent class in the derived class?

Aditya
  • 397
  • 2
  • 12
  • 4
    You *could* use casting like `((a)obj).var1` since fields are not polymorphic, but having field with same name in subclass doesn't look right and smells like [XY problem](https://meta.stackexchange.com/q/66377) – Pshemo May 14 '21 at 15:31
  • 1
    var1 is not inherited from class a, it is hidden by class b. – Joakim Danielson May 14 '21 at 15:31
  • 1
    Regarding calling *original* version of method (before overriding) you may be interested in: https://stackoverflow.com/questions/6896504/java-inheritance-calling-superclass-method/67491707#67491707 – Pshemo May 14 '21 at 15:38
  • @Pshemo Thank you! I got it! – Aditya May 14 '21 at 15:47

0 Answers0