Discuss various usage of super keyword with suitable example.
Question
Discuss various usage of super keyword with suitable example.
Solution
The super keyword in Python, Java, and other object-oriented programming languages has several uses, mainly related to inheritance and the use of methods from parent classes in child classes. Here are some of its uses:
-
Accessing inherited methods: The
superkeyword is used to call a method from a parent class in a child class. This is useful when you want to use the functionality of a parent method, but also add some additional functionality in your child class.For example, in Python:
class Parent: def my_method(self): print("Parent method") class Child(Parent): def my_method(self): super().my_method() print("Child method") c = Child() c.my_method()This will output:
Parent method Child methodHere,
super().my_method()is used to call themy_methodofParentclass inChildclass. -
Accessing inherited variables: Similar to methods,
supercan also be used to access variables from a parent class.For example, in Java:
class Parent { String name = "Parent"; } class Child extends Parent { String name = "Child"; void printName() { System.out.println(super.name); System.out.println(name); } } public class Main { public static void main(String[] args) { Child c = new Child(); c.printName(); } }This will output:
Parent ChildHere,
super.nameis used to access thenamevariable ofParentclass inChildclass. -
Calling parent constructor:
supercan be used to call the constructor of a parent class. This is useful when you want to initialize some variables in the parent class when creating an instance of the child class.For example, in Java:
class Parent { String name; Parent(String name) { this.name = name; } } class Child extends Parent { Child(String name) { super(name); } }Here,
super(name)is used to call the constructor ofParentclass inChildclass.
These are some of the main uses of the super keyword. It's a powerful tool that allows for more flexible and maintainable code by leveraging the principles of inheritance.
Similar Questions
What are the uses of super keyword?
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
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
rrect answerWhat would be the behavior if this() and super() used in a method?
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.