search
HomeJavajavaTutorialSuper Keyword in Java

Super Keyword in Java

Aug 30, 2024 pm 03:44 PM
java

Super is a keyword that is used to call a function or method in the superclass. This will be defined inside the sub-class. Methods that are only public and protected can be called by using this keyword. In other words, Private methods and static methods cannot be called using this. The super keyword in java can also be used in order to call the constructors of the parent class. Syntax, examples and further details of super keyword will be discussed in the following sections.

Syntax

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

super.> or super([0 or more arguments]);

How does Super Keyword work in Java?

As already mentioned, super can be used on several occasions.

  • To refer instance variable of an immediate parent class.
  • To refer to the method of an immediate parent class.
  • To refer to the constructor of an immediate parent class.

1. To Refer Instance Variable of an Immediate Parent Class

If the parent and child class have the same data members, the Super keyword can be used to access the field or data member of the parent class. Ambiguity for Java Virtual Machine can occur in this case.

Example:

Code:

class A {
protected String name="ann";
}
class B extends A {
public String name="Anna";
public void hello() {
System.out.println("I am  " + name);
System.out.println("I am  " + super.name);
}
}

Here, two classes A and B, have a common field name. A function printType() inside child class uses the super keyword to refer to the field in a parent class.

2. To Refer Method of An Immediate Parent Class

Method overriding is a process by which a child class declares the same function or method that is already available in the parent class. Suppose, if a call to the method happens from the object of the child class, then the method in the child class only will be called. In order to access the parent method, a super keyword can be used.

Example:

Code:

class A {
protected String name="ann";
public void hello() {
System.out.println("I am  " + name);
}
}
class B extends A {
public String name="Anna”;
public void hello() {
System.out.println("I am  " + name);
}
public void test()
{
hello();
super.hello();
}
}

Here, two classes, A and B, have the same method hello(). With the help of a super keyword in the test() function, it is possible to access the hello() method of a parent class.

3. To Refer Constructor of Immediate Parent Class

It is already known that a constructor (default) gets automatically called when the object of a class is created. The super keyword can be used to explicitly call the constructor of the superclass from the constructor of the subclass. Make sure that super is used only inside the constructor of the subclass, and it is the first statement inside that.

Example:

Code:

class A {
//constructor of parent class
A() {    System.out.println("I am Kavya Madhavan");
}
}
//child class
class B extends A {
//constructor of child class
B() {
super();
System.out.println("I am Dileep Menon");  } }

Examples of Super Keyword in Java

Below are the different examples mentioned:

Example #1

In the following program, a common variable name is present and super is used to call the variable in a parent class.

Code:

//Java program to illustrate Super keyword to refer instance variable
//parent class
class A {
protected String name="ann";
}
//child classs
class B extends A {
public String name="Anna";//variable which is same in parent class
//sample method
public void hello() {
System.out.println("I am  " + name);
System.out.println("I am  " + super.name);
}
}
//main class
public class SuperExample {
public static void main(String[] args) {
B objb=new B();//object of child class
objb.hello();//call the method in child class
}
}

Output:

Super Keyword in Java

Example #2

This program helps in demonstrating the super keyword while referring to the same method in a parent class. Here, hello() is a method that is available in both classes.

Code:

//Java program to illustrate Super keyword to refer same method in parent class
//parent class
class A {
protected String name="ann";
public void hello() {
System.out.println("I am  " + name);
}
}
//child classs
class B extends A {
public String name="Anna";//variable which is same in parent class
//sample method which is same in parent class
public void hello() {
System.out.println("I am  " + name);
}
//method to call the hello() method in parent and child class
public void test()
{
hello();
super.hello();
}
}
//main class
public class SuperExample {
public static void main(String[] args) {
B objb=new B();//object of child class
objb.test();//call the method in child class
} }

Output:

Super Keyword in Java

Example #3

This program calls the constructor of the parent class using the super keyword.

Code:

//Java program to illustrate Super keyword to refer constructor in parent class
//parent class
class A {
//constructor of parent class
A() {
System.out.println("I am Kavya Madhavan");
}
}
//child class
class B extends A {
//constructor of child class
B() {
super();
System.out.println("I am Dileep Menon");
}
}
//main class
public class SuperExample {
public static void main(String[] args) {
B objb=new B();//object of child class
}
}

Output:

Super Keyword in Java

Example #4

This program demonstrates a super keyword’s usage to refer to the parameterized constructor of a parent class.

Code:

//Java program to illustrate Super keyword to refer parameterised constructor in parent class
//parent class
class A {
//constructor of parent class
A() {
System.out.println("I am Kavya Madhavan");
}
//parameterised constructor
A(String name) {
System.out.println("I am " + name);
}
}
//child class
class B extends A {
//constructor of child class
B() {
super("Renuka");
System.out.println("I am Dileep Menon");
}
}
//main class
public class SuperExample {
public static void main(String[] args) {
B objb=new B();//object of child class
}
}

Output:

Super Keyword in Java

Conclusion

Super is a keyword in Java that is used to refer to the methods or functions, instance variables or attributes and constructors in the parent class. If a constructor is not declared, the compiler automatically creates a default constructor. Similarly, Compiler calls super() automatically if it is not declared. In this document, several aspects of the super keyword are explained in detail.

The above is the detailed content of Super Keyword in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)