Module 6: Inheritance and Polymorphism
Lesson focusInheritance Basics: The `extends` Keyword
Learn how to create a new class that inherits fields and methods from an existing class, promoting code reuse and establishing a type hierarchy.
What is Inheritance? Inheritance is a mechanism that allows a class (the subclass or child class) to inherit the properties and behaviors (fields and methods) of another class (the superclass or parent class).
The extends Keyword: You establish an inheritance relationship using the extends keyword. class Subclass extends Superclass { ... }
The 'is-a' Relationship: Inheritance represents an 'is-a' relationship. For example, a Dog is an Animal. A Car is a Vehicle. This is a good test to see if inheritance is the right design choice.
What is Inherited?
- Public and protected members (fields and methods) of the superclass are inherited by the subclass.
- Private members are not directly accessible by the subclass, but they are still part of the subclass object's structure. The subclass can interact with them through public or protected methods inherited from the superclass.
- Constructors are not inherited.
Benefits of Inheritance:
- Code Reusability: You can write common code once in a superclass and reuse it across multiple subclasses.
- Polymorphism: Inheritance is a prerequisite for polymorphism, which allows you to treat objects of different subclasses as if they were objects of the superclass.
Mini-Exercise: Create a Vehicle class with fields for brand and year, and a method start(). Then, create a Car class that extends Vehicle and adds a field for numberOfDoors.
// Superclass
class Animal {
String name;
public void eat() {
System.out.println(name + " is eating.");
]
}
// Subclass
class Dog extends Animal {
String breed;
public void bark() {
System.out.println("Woof!");
]
}
// In main
Dog myDog = new Dog();
myDog.name = "Buddy"; // Inherited from Animal
myDog.eat(); // Inherited from Animal
myDog.breed = "Golden Retriever";
myDog.bark();