Tutorials

Java OOP Tutorial

All Tutorials Learning Tools Login

Java OOP Tutorial · Chapter 8 of 10

Inheritance Intro

Reuse behavior through parent/child classes.

A child class can extend a parent class and reuse common fields/methods.

Example: Person as parent, Student as child.

Inheritance sample Try it Yourself »
public class Main {
    public static void main(String[] args) {
        Person person = new Person("Alex Tan");
        Student student = new Student("Mia Lopez", "BSCS");

        person.introduce();
        student.introduce();
        System.out.println("Course: " + student.getCourse());
    }
}
Person.java
public class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void introduce() {
        System.out.println("Hi, I am " + name + ".");
    }
}
Student.java
public class Student extends Person {
    private String course;

    public Student(String name, String course) {
        super(name);
        this.course = course;
    }

    public String getCourse() {
        return course;
    }

    @Override
    public void introduce() {
        System.out.println("Hello, I am " + getName() + " from " + course + ".");
    }
}

Classroom Tips

  • Keep inheritance hierarchies shallow in beginner projects.
  • Override methods only when the child needs different behavior.