
Java OOP – Chapter 4: Inheritance in Java
In this lesson, you’ll learn about Inheritance, one of the key pillars of Object-Oriented Programming. Java allows one class to inherit from another, enabling code reuse, extension of functionality, and hierarchical relationships between objects.
What is Inheritance?
Inheritance allows a class (called a subclass or child class) to inherit fields and methods from another class (called a superclass or parent class).
Java uses the extends keyword to define this relationship.
Benefits of Inheritance
Code reuse: Common behavior resides in the parent.
Hierarchy modeling: Naturally represent "is-a" relationships.
Flexibility: Subclasses can override or extend behavior.
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
Usage:
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.makeSound(); // Inherited
d.bark(); // Own method
}
}The super Keyword
You can use super to:
Call a superclass method.
Call a superclass constructor (from a subclass constructor).
class Animal {
Animal() {
System.out.println("Animal constructor called");
}
}
class Cat extends Animal {
Cat() {
super(); // Calls Animal constructor
System.out.println("Cat constructor called");
}
}Rules of Inheritance in Java
Java supports single inheritance only (one parent class per subclass).
Constructors are not inherited, but can be called using
super().Private members of the superclass are not accessible in the subclass directly.
Summary
Inheritance models "is-a" relationships and enables code reuse.
Use
extendsto create a subclass.Subclasses inherit accessible fields and methods from the parent class.
Use
superto reference the parent class.
Assignment: Lesson 4 – Inheritance
Objective:
Understand how to create subclasses, use extends, and invoke inherited methods.
Part 1: Conceptual Questions
Write short answers in a comment or text file:
What is the purpose of inheritance in OOP?
What does the
extendskeyword do?Can a subclass inherit private fields from a superclass?
Part 2: Coding Task
Create a superclass called Vehicle with:
Fields:
brand(String)Method:
drive()that printsbrand + " is driving"
Create a subclass called Car that:
Inherits from
VehicleHas its own method
playMusic()that prints"Playing music"
In the main() method:
Create a
CarobjectSet the brand to
"Tesla"Call both
drive()andplayMusic()
Github: https://github.com/tuanbeovnn/java-bootcamp/tree/java-bootcamp-oop-chapter4
