Chapter[12]: Understanding Inheritance in Java: A Beginner’s Guide

Automate This. By Mrigank Saxena
5 min readJan 13, 2025

--

Inheritance is a core concept in object-oriented programming (OOP) that allows classes to share attributes and methods, enhancing code reusability and readability. In this guide, we’ll explore inheritance using a practical example in Java to help us grasp the basics of creating classes and subclasses effectively.

Designed By Freepik

Key Concepts

  1. Main Class (Super Class): The base class that contains common attributes and methods.
  2. Subclass (Child Class): A specialized version of the main class that inherits properties from it and can also define its own unique attributes and behaviors.
  3. Inheritance: Allows the subclass to use the main class’s properties and methods without redefining them.

Example: Building a Person Class and Subclasses in Java

Imagine a main class Person that represents general attributes of any individual, like name, age, and gender. Subclasses such as Student, Doctor, Driver, and Engineer inherit from Person and add their unique characteristics. Here’s how this looks in Java.

Person
---------------------------------
| Attributes: name, age, gender |
| Methods: speak(), eat(), walk() |
---------------------------------
/ | \
Student Doctor Engineer
---------------- ---------------- -----------------
Attributes: Attributes: Attributes:
grade, school specialization field, skills
Methods: Methods: Methods:
study() diagnose() design()

Driver
-----------------
Attributes:
licenseType
Methods:
drive()

Explanation:

Base Class: Person

  • Attributes:
  • name: The individual's name (e.g., "John").
  • age: Their age (e.g., 25).
  • gender: Their gender (e.g., "Male").
  • Methods:
  • speak(): Allows a person to talk.
  • eat(): Represents a general eating action.
  • walk(): Represents a walking action common to all individuals.

These attributes and methods, for example speak(), and name are common and can be inherited by all subclasses, such as Engineer.

  1. Subclass: Student
  • Additional Attributes:
  • grade: The student’s current grade (e.g., "10th").
  • school: The name of the school (e.g., "Green Valley High").
  • Additional Method:
  • study(): Represents the act of studying.

2. Subclass: Doctor

  • Additional Attributes:
  • specialization: The doctor's area of expertise (e.g., "Cardiology").
  • Additional Method:
  • diagnose(): Represents diagnosing a patient.

3. Subclass: Engineer

  • Additional Attributes:
  • field: The engineering domain (e.g., "Software").
  • skills: A list of technical skills (e.g., "Java, Python").
  • Additional Method:
  • design(): Represents designing a project or solution.

4. Subclass: Driver

  • Additional Attribute:
  • licenseType: The type of driving license (e.g., "Commercial").
  • Additional Method:
  • drive(): Represents driving a vehicle.

Key Benefits of this Structure:

  • Inheritance: Common attributes (name, age, gender) and methods (speak(), eat(), walk()) are defined once in the Person class and inherited by all subclasses, avoiding redundancy.
  • Specialization: Each subclass defines attributes and methods specific to its role, making the design intuitive and logical.

Example Code Implementation in Java(A Basic Approach):

// Base Class
class Person {
String name;
int age;
String gender;

void speak() {
System.out.println(name + " is speaking.");
}
void eat() {
System.out.println(name + " is eating.");
}
void walk() {
System.out.println(name + " is walking.");
}
}
// Subclass: Student
class Student extends Person {
String grade;
String school;
void study() {
System.out.println(name + " is studying.");
}
}
// Subclass: Doctor
class Doctor extends Person {
String specialization;
void diagnose() {
System.out.println(name + " is diagnosing a patient.");
}
}
// Subclass: Engineer
class Engineer extends Person {
String field;
String[] skills;
void design() {
System.out.println(name + " is designing a solution.");
}
}
// Subclass: Driver
class Driver extends Person {
String licenseType;
void drive() {
System.out.println(name + " is driving a vehicle.");
}
}

This structured and detailed approach ensures logical inheritance and specialization while keeping the design maintainable and easy to understand for both technical and non-technical audiences.

Step 1: Defining the Person Class

The Person class includes general attributes (name, age, and gender) and a method to introduce a person.

public class Person {
// Common attributes
private String name;
private int age;
private String gender;

// Constructor to initialize attributes
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
// Method to introduce the person
public void introduce() {
System.out.println("Hello, my name is " + name + ", and I am " + age + " years old.");
}
// Getters for common attributes
public String getName()
{
return name;
}
public int getAge() { return age; }
public String getGender() { return gender; }
}

Here, the constructor initializes the common attributes, and the introduce() method allows any Person to introduce themselves.

Step 2: Creating the Subclass Student

The Student class extends Person, inheriting its attributes and introduce() method, while adding its unique attribute, rollNumber.

public class Student extends Person {
private int rollNumber;
// Constructor
public Student(String name, int age, String gender, int rollNumber) {
super(name, age, gender); // Calls the constructor of Person
this.rollNumber = rollNumber;
}
// Specific behavior for Student
public void study() {
System.out.println(getName() + " is studying."); // Using inherited getName() from Person
}
public int getRollNumber() { return rollNumber; }
}

Additional Subclasses

Each subclass inherits from Person and adds unique methods and attributes:

Doctor Subclass

public class Doctor extends Person {
private String specialization;
public Doctor(String name, int age, String gender, String specialization) {
super(name, age, gender);
this.specialization = specialization;
}
public void treatPatient() {
System.out.println(getName() + " is treating a patient in " + specialization + ".");
}
public String getSpecialization() { return specialization; }
}

Driver Subclass

public class Driver extends Person {
private String licenseNumber;
public Driver(String name, int age, String gender, String licenseNumber) {
super(name, age, gender);
this.licenseNumber = licenseNumber;
}
public void drive() {
System.out.println(getName() + " is driving.");
}
public String getLicenseNumber() { return licenseNumber; }
}

Engineer Subclass

public class Engineer extends Person {
private String field;
public Engineer(String name, int age, String gender, String field) {
super(name, age, gender);
this.field = field;
}
public void design() {
System.out.println(getName() + " is designing a project in " + field + ".");
}
public String getField() { return field; }
}

Explanation of Inheritance in Java

  • Common Attributes and Methods: The Person class includes attributes and methods shared by all subclasses, such as name, age, gender, and introduce().
  • Extending Functionality: Each subclass inherits common functionality while introducing unique methods (study() in Student, treatPatient() in Doctor, etc.), making each subclass specialized.
  • Calling Superclass Methods: Using super() in the subclass constructor allows the subclass to initialize the inherited attributes from the Person class, which btw is a great! feature.

Running the Code: Example Usage

Here’s how to create and interact with these classes:

public class Main {
public static void main(String[] args) {
Student student = new Student("Alice", 20, "Female", 101);
Doctor doctor = new Doctor("Dr. Smith", 45, "Male", "Cardiology");
Driver driver = new Driver("Mike", 30, "Male", "DL12345");
Engineer engineer = new Engineer("Jane", 35, "Female", "Civil Engineering");
student.introduce();
student.study();
doctor.introduce();
doctor.treatPatient();
driver.introduce();
driver.drive();
engineer.introduce();
engineer.design();
}
}

This guide demonstrates the inheritance concept in Java through a Person class and several specialized subclasses. With inheritance, each subclass automatically gains the Person class's attributes and methods while adding specific traits, resulting in efficient, readable, and reusable code. Understanding inheritance is fundamental to mastering object-oriented programming, enabling developers to design flexible and scalable applications.

check and download the sample code here.

.

.

.

Happy Coding!

--

--

Automate This. By Mrigank Saxena
Automate This. By Mrigank Saxena

Written by Automate This. By Mrigank Saxena

Join me as I share insights, tips, and experiences from my journey in quality assurance, automation, and coding! https://www.linkedin.com/in/iammriganksaxena/

No responses yet