Lets see some interesting java programs on super keyword.
Basically super keyword used to refer super class methods and variables. So now let us see how super will work in some scenarios. lets practice.
Try to answer below java programming interview questions for beginners.
Java programs asked in technical interview for freshers and experienced.
Program #1: What will be the output of below java program
package com.superkeywordinjava;
public Class SuperDemo{
int a,b;
}
package com.superkeywordinjava;
public Class Subdemo extends SuperDemo{
int a,b;
void disply(){
super.a=10;
super.b=20;
System.out.println(a);
System.out.println(b);
System.out.println(super.a);
System.out.println(super.b);
}
public static void main (String args[]) {
Subdemo obj= new Subdemo();
obj.a=1;
obj.b=2;
obj.disply();
}
}
1
2
10
20
Program #2: What will be the output of below java program
1
2
10
20
Program #3: Basic java programs for interview on super keyword
package com.superinterviewprograms;
public Class SuperDemo{
int a,b;
SuperDemo(int x, int y){
a=x;
b=y
System.out.println("Super class constructor called ");
}
}
package com.superinterviewprograms;
public Class Subdemo extends SuperDemo{
int a,b;
SubDemo(int x, int y){
super(10,20);
a=x;
b=y
System.out.println("Sub class constructor called ");
}
public static void main (String args[]) {
Subdemo obj= new Subdemo(1,2);
}
}
Super class constructor called
Sub class constructor called
Program #4: Java interview Program on super keyword
What will happen if our class constructor having super() call but our class not extending any class.
package com.superinterviewprograms;
public Class Sample{
Sample(){
super();
System.out.println("Sample class constructor called ");
}
public static void main (String args[]) {
Sample obj= new Sample();
}
}
Sample class constructor called
if our class not extending any class Yes still we can use super(); call in our class
Because in java every class will extend Object class by default this will be added by JVM.
But make sure we are using only super(); default call we can not place parameterized super call because Object class does not have any parameterized constructor.