Java4teachus

Tuesday, July 30, 2019

Super Keyword at Variable Level in Java

Super Keyword in java



Super is a keyword  or reference variable in java which is used  to refer the parent object.  Super is an implicit keyword which is created by JVM for each and every program during compile time to playing the 3 important role. They are:
  1. Super keyword at data members or variable level.
  2. Super keyword at Method level.
  3. Super keyword at Constructor Level.

Purpose Of Super Keyword


Whenever we inherit the base class features into derived class, There is a possibility that base class features are similar to derived class and JVM gets ambiguity problems.  In Order to differentiate between the base class features  and derived class features must be preceded by super keyword. 

Syntax
Syntax-of-Super-Keyword-in-java.jpeg


Super Keyword at Data Member/Variable Level.


Whenever the derived class inherit the base class data members, there is a possibility that base class data members are similar to the  derived class data members and JVM gets ambiguity.

In Order to differentiate between base class data members  and derived class data members, in the context of derived class and base class data members must be preceded by super keyword.

Syntax
Syntax-of-Super-keyword-at-Variable-level-in-java
If we do not write a super keyword before base class data members then that data members is consider by JVM like as derived class data members and base class data members will be hidden.

Program:1

class BaseClass
{
int a;
}
class DerivedClass extends BaseClass
{
int a,b;
void set(int x,int y)
{
super.a=x;
this.a=y;
}
void add()
{
b=super.a+this.a;
}
void display()
{
System.out.println("value of Baseclass :" + super.a);
System.out.println("value of Derivedclass :" + this.a);
System.out.println("Summ :"+b);
}
}
class BaseDerivedClassEx
{
public static void main(String[] args) 
{
DerivedClass d=new DerivedClass();
d.set(10,20);
d.add();
d.display();
}
}
Output
Super-At-Variable-level-program.jpeg

Program :2

class First
{
String name="Java4";
}
class SecondName extends First
{
String name="Teachus";
void display()
{
String merge=super.name+name;
System.out.println("Full Name: "+ merge);
}
}
class FullName
{
public static void main(String[] args) 
{
SecondName s=new SecondName();
s.display();
}

}
Output
Super-Keyword-at-Variable-level-in-java.jpeg


1 comment:

  1. Thanks for sharing useful information with us.. It really helpful to me..I always prefer to read the quality content and this thing I found in you post. thanks for sharing with us..
    Visit this site

    ReplyDelete

Thanks for visiting my site..