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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.