Java Inheritance, Overriding and Overloading
Inheritance is one of the cornerstones of object-oriented programming, allowing us to create hierarchical class structures and achieve code reuse. Closely related to inheritance is method overriding, while another easily confused concept is method overloading. This chapter will explain the relationships and differences between these three concepts in detail.
Inheritance
Inheritance allows one class (subclass) to acquire the non-private attributes and methods of another class (parent class). Subclasses can use parent class members as if they were their own.
- Superclass: Also called base class, is the class being inherited from.
- Subclass: Also called derived class, is the class that inherits from the parent class.
In Java, the extends keyword is used to implement inheritance.
The super Keyword
The super keyword is used to reference members of the direct parent class from within a subclass.
- Calling parent class constructor:
super()must be the first statement in a subclass constructor, used to call the parent class constructor. - Calling parent class methods:
super.methodName()can be used to call the parent class version of a method that has been overridden in the subclass.
Method Overriding
When a subclass is not satisfied with a particular method implementation provided by the parent class, it can provide its own version of the method with the same name and parameters. This process is called method overriding.
Overriding Rules:
- Method name and parameter list must be exactly the same as the parent class.
- The subclass's return type must be the same as or a subtype of the parent class's return type.
- The access modifier of the subclass method cannot be more restrictive than that of the parent class method (e.g., if parent is
public, subclass cannot beprotected). - It's recommended to use the
@Overrideannotation, which allows the compiler to check if this is a valid override.
Method Overloading
Method overloading means that within the same class, you can have multiple methods with the same name, as long as their parameter lists are different (different in number, type, or order of parameters). Overloading is unrelated to return type.
Overriding vs. Overloading
This is a very important comparison in Java and a common interview question.
Applications of the final Keyword
-
finalmethod: If a method in a parent class is declared asfinal, it cannot be overridden by any subclass. -
finalclass: If a class is declared asfinal, it cannot be inherited by any class. For example, Java'sStringclass isfinal.