What are the uses of super keyword?
Question
What are the uses of super keyword?
Solution
The super keyword in programming, particularly in object-oriented programming languages like Java and Python, has several uses:
-
Accessing Superclass Methods: The
superkeyword can be used to call a method in the superclass that has been overridden in a subclass. This allows the subclass to use the original method from the superclass, even if it has a method with the same name. -
Accessing Superclass Constructors: In Java, the
superkeyword can also be used to call the constructor of the superclass. This is useful when you want to create an instance of the subclass, but need to initialize some aspects of the object in the superclass. -
Accessing Superclass Variables: If a subclass has a variable with the same name as a variable in the superclass, the
superkeyword can be used to access the variable from the superclass.
Here's a step-by-step example in Java:
// Superclass
public class Animal {
String name = "Animal";
public void eat() {
System.out.println("The animal eats");
}
}
// Subclass
public class Dog extends Animal {
String name = "Dog";
@Override
public void eat() {
System.out.println("The dog eats");
}
public void eatAndCallSuper() {
super.eat(); // This will call the eat method from Animal class
System.out.println("Name in superclass: " + super.name); // This will print "Animal"
}
}
In this example, the Dog class is a subclass of Animal. The Dog class overrides the eat method from Animal, but can still call the eat method from Animal using super.eat(). The Dog class also has a variable name that hides the name variable from Animal, but can still access the name variable from Animal using super.name.
Similar Questions
Discuss various usage of super keyword with suitable example.
What is the purpose of the super() keyword in Java?
The use of "super" keyword is for Calling multiple constructor in same class Calling multiple methods Calling base class constructor in derived class Creating object of the class
What is the purpose of the super() function in Python?
Super keyword in java is used toSelect one:Refer immediate parent class instance variables.Invoke immediate parent class methods.Invoke immediate parent class constructor.All
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.