Home » Java programming language

super keyword and super() method in Java



Here, we are going to learn about super keyword and super() method in java? What are usage of super and super() in java?
Submitted by Preeti Jain, on February 28, 2018

Java 'super' keyword

  • super keyword is introduced in java.
  • With the help of super keyword, we can access the instance variable of the parent class (i.e. when parent class and child class contains variable having the same name then we can access the parent class variable by using super keyword).

Example:

class Parent{
	String str = "I am MCA" ;
}

class Child extends Parent{
	String str;

	Child(String str){
		System.out.println(super.str);
	}
	
	public static void main(String[] args){
		Child ch = new Child("I am Preeti Jain");
	}
}

Output

D:\Java Articles>java Child
I am MCA
  • With the help of super keyword, we can access the method of the parent class (i.e. when parent class and child class contains method having the same name then we can access the parent class method by using super keyword).

Example:

class ParentMethod{
	public void print(){
		System.out.println("I am in Parent Class");
	}
}

class ChildMethod extends ParentMethod{
	public void print(){
		super.print();
		System.out.println("I am in Child Class");
	}
	public static void main(String[] args){
		ChildMethod cm = new ChildMethod();
		cm.print();
	}
}

Output

D:\Java Articles>java ChildMethod
I am in Parent Class
I am in Child Class

Java 'super()' method

  • super() method introduced in java.
  • With the help of super() method, we can call parent class constructor.

Example:

class ParentConstructor{
	ParentConstructor(){
		System.out.println("I am in parent constructor");
	}
}

class ChildConstructor extends ParentConstructor{
	ChildConstructor(){
		super();
	}
	
	public static void main(String[] args){
		ChildConstructor cc = new ChildConstructor();
	}
}

Output

D:\Java Articles>java ChildConstructor
I am in parent constructor





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions





© https://www.includehelp.com (2015-2018), Some rights reserved.




close Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.