super is a keyword created by JVM and supplied to each and every Java program to differentiate between BaseClass feature and DerivedClass feature
If data member of BaseClass and DerivedClass are same then JVM gets an ambiguity. To solve the above problem super keyword is used
class A{
int a;
}
class B extends A{
int a;
int b;
void set(int x, int y){
// a = x; // base class variable
super.a = x; // parent class variable
a = y; // child class variable
}
void add(){
// b = a + a; // adds the a's of
b = super.a + a; // ParentClassVar + ChildClassVar
System.out.println(b);
}
}
class Demo{
public static void main(String args[]){
B obj = new B();
obj.set(100, 200);
obj.add();
}
}code here
First the data member of BaseClass will be initialized then data member of ChildClass will be initialized
class A{ // constructor
A(){
System.out.println("Base Class");
}
}
class B extends A{
B(){
System.out.println("Child Class");
}
}
class Demo{
public static void main(String args[]){
B obj = new B();
}
}class A{
A(){
System.out.println("Base default");
}
A(int a){
System.out.println("Base Class Parameter");
}
class B extends A{
B(){
Super(100);
System.out.println("Child default");
}
B(int a){
this(100, 200)
System.out.println("Child single parameter");
}
B(int x, int y){
System.out.println("Child double parameter");
}
}
}
class Demo{
public static void main(String args[]){
B obj = new B(100);
B obj = new B();
}
}
/* Output
Base default
Child double parameter
Child single parameter
Base Class Parameter
Child default
*/