You are here: Home / Topics / Program to use super to access super class instance variables in Java

Program to use super to access super class instance variables in Java

Filed under: Java on 2023-09-17 06:59:35

//Program to use super to access super class instance variables 
//when sub class instance variables hides the super class instance variables.

class A 
{
int x;
}

class B extends A 
{
int  x;   // this x hides the x in A

B(int a, int b) 
{
 super.x = a;   // x in A
 x = b;    // x in B
}

void show() 
{
 System.out.println("x in superclass: " + super.x);
 System.out.println("x in subclass: " + x);
}
}

class  HideSuperClassVar 
{
public static void main(String args[ ]) 
{
 B ob = new B(1, 2);

 ob.show();
}
}

 

Output:

x in superclass: 1
x in subclass: 2

About Author:
M
Mr. Dubey     View Profile
Founder of MCQ Buddy. I just like to help others. This portal helps students in getting study material free.