Below is a more detailed description of some key features of OOP in Java:
Inheritance
1. Basic Definition
When a class reuses properties and methods of another class, we say "inheritance" has occurred.
The reusing class is called the "child class" or "subclass," while the class it inherits from is called the "super class" or "parent class."
2. Handling Constructors in Inheritance
In the scenario where the parent class lacks a default constructor, the child class must have at least one constructor and must call at least one constructor of the parent class. This ensures that the initialization of the parent class's properties is also performed when creating an object of the child class.
3. Overriding
Overriding occurs at runtime when a method in the child class has the same signature (method signature) as in the parent class.
Overriding can be used to reuse the logic of the parent class while still being able to change the logic as per the needs of the child class.
4. Overloading
Overloading occurs at compile time and involves defining multiple methods with the same name in a class but with different parameter lists
Overloading enhances flexibility and utility when using methods with different parameter types.
Let's take a look at an example:
In this example:
"Animal" is the parent class with an attribute 'name' and a method 'makeSound'.
"Dog" is the child class inheriting from "Animal", overriding the 'makeSound' method to change the logic, and adding an overloaded 'makeSound' method to display 'Woof!' multiple times.
In the "main" method, we create objects from both the parent and child classes to illustrate their usage and the characteristics of OOP.
Comentários