Basic Inheritance (extends)
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 20 of 87.
Inheritance is one of the core pillars of OOP. It allows a class to acquire the properties and methods of another class, promoting code reuse and establishing a natural hierarchy between classes.
In Java, you create an inheritance relationship using the extends keyword. The class that inherits is called the subclass (or child class), and the class being inherited from is the superclass (or parent class).
public class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " is eating");
}
public String getName() {
return name;
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name); // Calls parent constructor
}
public void bark() {
System.out.println(getName() + " says woof!");
}
}The Dog class automatically inherits the eat() method and getName() method from Animal. It can also define its own methods like bark():
Dog myDog = new Dog("Buddy");
myDog.eat(); // Inherited: "Buddy is eating"
myDog.bark(); // Own method: "Buddy says woof!"Think of inheritance as an "is-a" relationship. A Dog is an Animal, so it makes sense for Dog to extend Animal. This relationship lets you build specialized classes that share common functionality while adding their own unique behaviors.
Challenge
EasyLet's build a simple vehicle system that demonstrates inheritance in action. You'll create a parent class that holds common vehicle properties, and a child class that extends it with specialized behavior.
You'll organize your code across three files:
Vehicle.java: Create the parent class that represents any vehicle. It should have:- A private field for the vehicle's
brand(String) - A constructor that accepts the brand name and uses
super()isn't needed here since Vehicle is the parent - A method
getBrand()that returns the brand - A method
start()that prints:[brand] is starting
- A private field for the vehicle's
Motorcycle.java: Create a subclass that extends Vehicle. A motorcycle is a vehicle, so this "is-a" relationship makes inheritance appropriate. Your Motorcycle should:- Use
extendsto inherit from Vehicle - Have a constructor that takes the brand and passes it to the parent using
super(brand) - Add its own method
wheelie()that prints:[brand] is doing a wheelie!
- Use
Main.java: Bring everything together by creating a Motorcycle object and demonstrating both inherited and unique behaviors. You'll receive one input: the brand name. Print two lines by calling:- The inherited
start()method - The Motorcycle's own
wheelie()method
- The inherited
You will receive one input: the brand name (String) for your motorcycle.
Notice how your Motorcycle automatically has access to start() and getBrand() without rewriting them - that's the power of inheritance!
Cheat sheet
Use the extends keyword to create an inheritance relationship between classes:
public class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " is eating");
}
public String getName() {
return name;
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name); // Calls parent constructor
}
public void bark() {
System.out.println(getName() + " says woof!");
}
}The subclass (child) inherits all methods from the superclass (parent) and can add its own:
Dog myDog = new Dog("Buddy");
myDog.eat(); // Inherited method
myDog.bark(); // Own methodUse super() in the subclass constructor to call the parent class constructor.
Inheritance represents an "is-a" relationship between classes.
Try it yourself
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String brand = scanner.nextLine();
// TODO: Create a Motorcycle object with the brand
// TODO: Call the inherited start() method
// TODO: Call the wheelie() method
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System