Java Super Keyword

  1. Call Base Class Constructor using super in Java
  2. Call Base Class Method using super in Java
  3. Access Base Class Variables using super in Java
  4. Access Inherited Class functionalities using super in Java

Note
Here I am using,
OS : Linux (Ubuntu 12.04)
IDE : Eclipse Tool
Eclipse : Juno (Version 4.2.0)
Package : Default package

A. Call Base Class Constructor using super in Java


Super_Ex1.java

public class Super_Ex1 {
	
	public Super_Ex1(String str) {
		
		System.out.println("Base Class Constructor " + str);
	}
}
 
class SubClass extends Super_Ex1 {
	
	public SubClass(String str) {
		
		super(str);
		System.out.println("Sub Class Constructor " + str);
	}
}
 
class MainClass {
	
	public static void main(String args[]) {
		
		SubClass obj = new SubClass("called");
	}
}

Sample Output

Base Class Constructor called
Sub Class Constructor called




B. Call Base Class Method using super in Java


Super_Ex2.java

public class Super_Ex2 {
	
	void display() {
		
		System.out.println("Base Class method called");
	}
}
 
class SubClass extends Super_Ex2 {
	
	void display() {
		
		super.display();
		System.out.println("Sub Class method called");
	}
}
 
class MainClass {
	
	public static void main(String args[]) {
		
		SubClass obj = new SubClass();
		obj.display();
	}
}

Sample Output

Base Class method called
Sub Class method called

Modify below code in display()

void display() {
		
	//super.display();
	System.out.println("Sub Class method called");
}

Sample Output

Sub Class method called




C. Access Base Class Variables using super in Java


Super_Ex3.java

public class Super_Ex3 {
	
	int a = 10;
}
 
class SubClass extends Super_Ex3 {
	
	void display() {
		
		int a = super.a;
		System.out.println("The value is : " + a);
	}
}
 
class MainClass {
	
	public static void main(String args[]) {
		
		SubClass obj = new SubClass();
		obj.display();
	}
}

Sample Output

The value is : 10




D. Access Inherited Class functionalities using super in Java


Super_Ex4.java

public class Super_Ex4 {
	
	int a = 10;
}
 
class SubClass1 extends Super_Ex4 {
	
	int b = 20;
}
 
class SubClass2 extends SubClass1 {
	
	void display() {
		
		int c = super.a + super.b;
		
		System.out.println("The Addition is : " + c);
	}
}
 
class MainClass {
	
	public static void main(String args[]) {
		
		SubClass2 obj = new SubClass2();
		obj.display();
	}
}

Sample Output

The Addition is : 30

Modify below code in SubClass1.java

class SubClass1 extends Super_Ex4 {
	
	int a = 30;
	int b = 20;
}

Sample Output

The Addition is : 50






SHARE THIS PAGE



product 2

product 3

Feedbacks : balaji.scz@gmail.com