AI Hints
Home›Java Tutorial›Encapsulation, Inheritance and super
Java · Lesson 74 of 120

Inheritance

Build on another class.

⏱ 2 min read▶ Video at 1:32:59🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Many classes share things. Dogs and cats are both animals. They both have a name, and they both eat. Inheritance lets one class build on another, and reuse its code.

  • Shared features
  • Dogs and cats are animals
  • Reuse the code

Animal.java

Animal is the parent class, also called the superclass. It has a name, and an eat method. The name is protected, so child classes can use it too.

Main.javajava
public class Animal {
    protected String name;

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

    public void eat() {
        System.out.println(name + " is eating.");
    }
}

Dog.java

Extends Animal means a dog is an animal. Dog gets the name, and eat, for free. It adds its own method, fetch, that only dogs have.

Main.javajava
public class Dog extends Animal {
    public Dog(String name) { super(name); }

    public void fetch() {
        System.out.println(name + " fetches the ball!");
    }
}

Using them

Rex can eat, inherited from Animal, and fetch, from Dog. A plain animal can eat, but can't fetch. Instance of checks whether an object is a kind of something. Run it. Rex eats, and fetches. And rex is indeed an animal.

Main.javajava
public class Main {
    public static void main(String[] args) {
        Dog rex = new Dog("Rex");
        rex.eat();
        rex.fetch();
        Animal generic = new Animal("Some animal");
        generic.eat();
        System.out.println(rex instanceof Animal);
    }
}
Output
Rex is eating.
Rex fetches the ball!
Some animal is eating.
true
Also uses Animal.java
public class Animal {
    protected String name;

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

    public void eat() {
        System.out.println(name + " is eating.");
    }
}
Also uses Dog.java
public class Dog extends Animal {
    public Dog(String name) { super(name); }

    public void fetch() {
        System.out.println(name + " fetches the ball!");
    }
}

Inheritance in Java

A class extends exactly one parent. The child gets the parent's fields and methods, and can add its own. Every class in Java secretly extends a class called Object. That's where to string comes from.

keyvalue
extendsone parent only
Child getsfields and methods
Child addsits own extras
Top of the treeObject

Summary

A child class extends a parent, gets its fields and methods, and adds its own. It's an is a relationship. Next, the super keyword.

Key takeaways
  • class Dog extends Animal
  • Reuse code
  • is-a
Next up: super — talk to the parent