What is the function of the `super` keyword in Java?

Study for the Java Technical Interview! Test your knowledge with multiple choice questions, each offering hints and explanations. Get ready to ace your Java exam!

Multiple Choice

What is the function of the `super` keyword in Java?

Explanation:
The `super` keyword in Java serves the specific function of accessing methods and constructors from a superclass. When a subclass needs to invoke a method or a constructor that exists in its immediate parent class, it uses the `super` keyword to refer to the superclass and differentiate between members of the superclass and those within the subclass. This is particularly useful in scenarios where an overridden method in the subclass needs to call the version of the method defined in the parent class, allowing for the appropriate behavior to be executed. Additionally, when calling a constructor of the superclass, `super` can be used in the subclass constructor to ensure that the superclass is properly initialized before any subclass-specific initialization occurs. For example: ```java class Parent { Parent() { System.out.println("Parent constructor"); } void show() { System.out.println("Parent show method"); } } class Child extends Parent { Child() { super(); // Calls the constructor of Parent System.out.println("Child constructor"); } void show() { super.show(); // Calls the show method from Parent System.out.println("Child show method"); } } ``` In this example, the `super()` call in the `Child

The super keyword in Java serves the specific function of accessing methods and constructors from a superclass. When a subclass needs to invoke a method or a constructor that exists in its immediate parent class, it uses the super keyword to refer to the superclass and differentiate between members of the superclass and those within the subclass.

This is particularly useful in scenarios where an overridden method in the subclass needs to call the version of the method defined in the parent class, allowing for the appropriate behavior to be executed. Additionally, when calling a constructor of the superclass, super can be used in the subclass constructor to ensure that the superclass is properly initialized before any subclass-specific initialization occurs.

For example:


class Parent {

Parent() {

System.out.println("Parent constructor");

}

void show() {

System.out.println("Parent show method");

}

}

class Child extends Parent {

Child() {

super(); // Calls the constructor of Parent

System.out.println("Child constructor");

}

void show() {

super.show(); // Calls the show method from Parent

System.out.println("Child show method");

}

}

In this example, the super() call in the `Child

Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy