20-Need For Inheritance
Inheritance in Java
Object-Oriented Programming (OOP):
When discussing Object-Oriented Programming (OOP), concepts like classes, objects, and
encapsulation are fundamental. One of the most important concepts within OOP is
inheritance.
The Need for Inheritance
Understanding "Is-A" and "Has-A" Relationships:
● Has-A Relationship:
Consider a computer as an abstract concept. It could be a laptop, desktop, or mobile
device—it's not specific, just a hardware device. When discussing a desktop, for
example, we might say that the desktop has hardware, has a keyboard, and has a
mouse. These relationships describe composition, where an
object contains other objects.
● Is-A Relationship:
Now, take the example of a Toyota Fortuner, a popular car in
India. When referring to it, we say "Fortuner is a Car." The
phrase "is a" emphasizes the relationship of inheritance. Here, the
Fortuner inherits the general characteristics of a car but also
includes specific features that distinguish it from other cars.
Real-World Example of Inheritance
In Java, inheritance is a mechanism where one class can inherit properties and methods from
another class. Let’s consider the example of a calculator:
● Basic Calculator (Calc):
This class might include variables and methods for basic operations like addition,
subtraction, and division.
● Advanced Calculator (AdvCalc):
This class represents a scientific calculator with advanced features, in addition to the
basic operations.
Inheritance Relationship:
● AdvCalc inherits from Calc. This means AdvCalc can use the properties and methods
of Calc and add its own specialized features.
Key Terms in Inheritance
● Parent Class / Superclass / Base Class:
The class from which properties and methods are inherited. In this example, Calc is
the parent class.
● Child Class / Subclass / Derived Class:
The class that inherits from another class. Here, AdvCalc is the child class.
● Inheritance and the extends Keyword in Java
● In Java, inheritance is implemented using the extends keyword. This keyword allows
one class (the child class or subclass) to inherit the properties and methods of another
class (the parent class or superclass).
● Syntax: