Inheritance
Inheritance in Java
Welcome back! Now that you have a solid understanding of classes and objects in Java, it's time to build on that knowledge by exploring inheritance. Consider it a natural progression in our journey into object-oriented programming (OOP).
Inheritance allows you to create a new class based on an existing class. By using inheritance, you can reuse code, add new features, and make your programs easier to manage and understand. Let's dive in and see what it's all about.
What We'll Cover
In this lesson, you'll understand how to use inheritance in Java. We'll cover:
- What Inheritance Is
- How to Implement Inheritance in Java
- Why Inheritance Is Beneficial
You'll also learn about chaining inheritance and how to manage multiple inheritance using interfaces.
What Inheritance Is
Inheritance is a way to establish a relationship between a new class (derived class) and an existing class (base class). The derived class inherits properties and behaviors (methods) from the base class. To better understand this concept, we'll use an example involving a Person class as the base class and a Student class as the derived class. This example will help demonstrate how properties and methods are inherited from the base class and how additional features can be added to the derived class.
Base Class: Person
Let’s start by defining a Person class, which will act as the base class in our example:
In this snippet, the Person class is defined with private attributes name and age. It also includes a constructor to initialize these attributes and a display method to print the details.
Derived Class: Student
Now, let’s create a Student class that inherits from the Person class:
In the Student class, we use the extends keyword to inherit from Person. The Student class reuses the name and age attributes from the Person class, and it adds a new attribute, major. The constructor uses the super keyword to call the base class constructor and initialize the inherited properties. The Student class also adds a displayMajor method to show the student’s major.
