1.2.2 Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class to inherit properties and methods from another class. This promotes code reusability and helps in creating a hierarchical structure of classes.
Key Concepts
1. Superclass and Subclass
A superclass, also known as a parent class or base class, is the class whose properties and methods are inherited. A subclass, also known as a child class or derived class, is the class that inherits from the superclass. The subclass can add new properties and methods or override existing ones.
2. extends Keyword
The extends
keyword is used in Java to indicate that a class is inheriting from another class. For example, if class B
extends class A
, class B
inherits all the non-private members of class A
.
3. Method Overriding
Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. The method in the subclass must have the same name, return type, and parameters as the method in the superclass.
4. super Keyword
The super
keyword is used to refer to the superclass from within a subclass. It can be used to call the superclass's constructor, methods, or access its properties.
Examples and Analogies
Superclass and Subclass Example
Consider a superclass Animal
with properties like name
and age
, and methods like eat()
and sleep()
. A subclass Dog
can inherit these properties and methods, and add its own specific methods like bark()
.
class Animal { String name; int age; void eat() { System.out.println("The animal is eating."); } void sleep() { System.out.println("The animal is sleeping."); } } class Dog extends Animal { void bark() { System.out.println("The dog is barking."); } }
extends Keyword Example
In the example above, the Dog
class uses the extends
keyword to inherit from the Animal
class. This means that an instance of Dog
can call methods like eat()
and sleep()
that are defined in the Animal
class.
Method Overriding Example
Suppose the Animal
class has a method makeSound()
that prints "The animal makes a sound." The Dog
class can override this method to print "The dog barks."
class Animal { void makeSound() { System.out.println("The animal makes a sound."); } } class Dog extends Animal { @Override void makeSound() { System.out.println("The dog barks."); } }
super Keyword Example
If the Dog
class wants to call the makeSound()
method from the Animal
class, it can use the super
keyword.
class Dog extends Animal { @Override void makeSound() { super.makeSound(); // Calls the makeSound() method from Animal System.out.println("The dog barks."); } }
By understanding and applying these concepts, you can create more organized and reusable code in Java.