Java Core: Inheritance
Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows you to create new classes (child/subclasses) based on existing classes (parent/superclasses). It promotes code reusability and establishes a "is-a" relationship between classes.
Key Concepts:
- Parent Class (Superclass/Base Class): The class being inherited from. It defines common properties and behaviors.
- Child Class (Subclass/Derived Class): The class that inherits from the parent class. It inherits all the members (fields and methods) of the parent class and can add its own unique members or override existing ones.
extendsKeyword: Used to indicate inheritance in Java.- "Is-a" Relationship: A child class is-a type of its parent class. For example, a
Dogis-aAnimal. - Code Reusability: Avoids redundant code by inheriting common attributes and methods.
- Hierarchy: Inheritance creates a hierarchical relationship between classes, representing a specialization of more general concepts.
Syntax:
class ParentClass {
// Fields and methods of the parent class
}
class ChildClass extends ParentClass {
// Fields and methods of the child class
}
Example:
// Parent class: Animal
class Animal {
String name;
String color;
public Animal(String name, String color) {
this.name = name;
this.color = color;
}
public void eat() {
System.out.println(name + " is eating.");
}
public void sleep() {
System.out.println(name + " is sleeping.");
}
}
// Child class: Dog, inheriting from Animal
class Dog extends Animal {
String breed;
public Dog(String name, String color, String breed) {
// Call the parent class's constructor using 'super()'
super(name, color);
this.breed = breed;
}
public void bark() {
System.out.println(name + " is barking!");
}
// Override the eat() method from the Animal class
@Override
public void eat() {
System.out.println(name + " the " + breed + " is happily munching on food.");
}
}
// Child class: Cat, inheriting from Animal
class Cat extends Animal {
public Cat(String name, String color) {
super(name, color);
}
public void meow() {
System.out.println(name + " is meowing!");
}
}
public class InheritanceExample {
public static void main(String[] args) {
Dog myDog = new Dog("Buddy", "Golden", "Golden Retriever");
Cat myCat = new Cat("Whiskers", "Gray");
myDog.eat(); // Calls the overridden eat() method in Dog
myDog.sleep(); // Calls the eat() method inherited from Animal
myDog.bark();
myCat.eat(); // Calls the eat() method inherited from Animal
myCat.sleep();
myCat.meow();
}
}
Explanation:
- The
DogandCatclasses extend theAnimalclass, inheriting itsname,color,eat(), andsleep()members. - The
Dogclass adds its own memberbreedand overrides theeat()method to provide a more specific implementation for dogs. - The
super()keyword is used in the child class's constructor to call the parent class's constructor, ensuring that the inherited fields are initialized. - The
@Overrideannotation is used to indicate that a method is overriding a method from the parent class. This is good practice for clarity and helps the compiler catch errors if the method signature doesn't match the parent class's method.
Types of Inheritance (Java only supports single inheritance):
- Single Inheritance: A class can inherit from only one parent class. This is the type of inheritance supported by Java.
- Multilevel Inheritance: A class inherits from a parent class, which in turn inherits from another parent class, and so on.
- Hierarchical Inheritance: Multiple classes inherit from a single parent class.
- Multiple Inheritance: A class inherits from multiple parent classes. Java does not directly support multiple inheritance of classes (it uses interfaces instead - covered in polymorphism).
Benefits of Inheritance:
- Code Reusability: Reduces code duplication.
- Modularity: Promotes a well-organized and modular code structure.
- Extensibility: Allows you to easily extend existing functionality without modifying the original code.
- Maintainability: Makes code easier to maintain and update.
- Polymorphism: Enables polymorphism (discussed in the next section), which allows you to treat objects of different classes in a uniform way.
Limitations of Inheritance:
- Tight Coupling: Child classes are tightly coupled to their parent classes. Changes in the parent class can potentially break the child classes.
- Fragile Base Class Problem: Modifying the base class can have unintended consequences in derived classes.
- Single Inheritance Restriction: Java's single inheritance limitation can sometimes be restrictive.
This provides a comprehensive overview of inheritance in Java. Understanding inheritance is crucial for building robust and maintainable object-oriented applications. The next step is to explore polymorphism, which builds upon the foundation of inheritance.