What does the super() function do? Tell me more about the principles of OOP (encapsulation, inheritance, polymorphism, abstraction).
sobes.tech AI
Answer from AI
The super() function in programming languages like Java or Python is used to call the constructor or method of the parent class from a subclass. This allows extending or overriding behavior while maintaining access to the base implementation.
Object-Oriented Programming principles:
-
Encapsulation — hiding the internal implementation of an object and providing access to data only through methods. This helps protect data and control its modification.
-
Inheritance — a mechanism that allows creating a new class based on an existing one, inheriting its properties and methods, which promotes code reuse.
-
Polymorphism — the ability of objects of different classes to respond to the same messages (method calls) differently. This is achieved through method overriding.
-
Abstraction — highlighting the essential characteristics of an object, hiding implementation details. It allows working with objects at the interface or abstract class level.
Example in Java using super():
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
super.sound(); // call to parent method
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
}
}
Output will be:
Some sound
Bark
This demonstrates how a subclass extends the behavior of a parent class by calling its method via super().