07-08 Inheritance and Polymorphism
07-08 Inheritance and Polymorphism
Inheritance in Java
Concept: Inheritance is one of the core principles of Object-Oriented Programming (OOP) in Java,
allowing a new class (subclass) to inherit fields and methods from an existing class (superclass).
This mechanism promotes code reusability and establishes a natural hierarchical relationship
between classes.
Importance:
1. Code Reusability: Allows developers to reuse existing code, reducing redundancy.
2. Maintenance: Easier to maintain and update code since changes in the superclass
automatically propagate to subclasses.
3. Hierarchy Representation: Models real-world relationships naturally, representing "is-a"
relationships.
Reason:
Inheritance simplifies the software design by allowing classes to be built upon existing ones,
enhancing the abstraction and encapsulation of code.
How to Implement: To create a subclass from a superclass, use the extends keyword.
// Superclass
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Subclass
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class MathOperations {
int add(int a, int b) {
return a + b;
}
class Printer {
void print(String s) {
System.out.println(s);
}
void print(int i) {
System.out.println(i);
}
Summary
Inheritance allows new classes to inherit properties and behavior from existing classes, promoting
code reuse and logical hierarchy. Polymorphism enables methods to do different things based on
the object it is acting upon, providing flexibility and reusability. Together, they form the backbone
of object-oriented design, enabling robust and maintainable software systems.