Skip to main content

Section 8.6 Java Inheritance Syntax

In Java, you establish an inheritance relationship using the extends keyword in your class declaration.
When a class extends another class, it automatically inherits all non-private members (fields and methods) from the superclass.
The general syntax looks like this:
public class SubclassName extends SuperclassName {
    // Additional fields and methods
    // unique to this subclass
}
For example, if Monster extends Entity, it inherits all non-private fields and methods from Entity automatically:
public class Monster extends Entity {
    // extra fields or methods for Monster can go here
}

Subsection 8.6.1 A Complete Inheritance Example

Below is a fuller example. The superclass Entity stores a health field, plus methods for initializing and modifying this health. The subclass Player automatically gains those fields and methods, but also adds its own unique ones.
// File: Entity.java
public class Entity {
    protected int health;
    protected int maxHealth;
    protected String name;
    
    public Entity(String name, int initialHealth) {
        this.name = name;
        this.maxHealth = initialHealth;
        this.health = initialHealth;
    }

    public void takeDamage(int amount) {
        // Common damage calculation logic
        health -= amount;
        if (health < 0) {
            health = 0;
        }
        System.out.println(name + " takes " + amount + " damage. Health: " + health);
    }
    
    public void heal(int amount) {
        health += amount;
        if (health > maxHealth) {
            health = maxHealth;
        }
        System.out.println(name + " heals for " + amount + ". Health: " + health);
    }

    public int getHealth() {
        return health;
    }
    
    public String getName() {
        return name;
    }
}

// File: Player.java
public class Player extends Entity {
    private int experiencePoints;
    private int level;

    public Player(String playerName, int initialHealth) {
        super(playerName, initialHealth); // calls the Entity constructor
        this.experiencePoints = 0;
        this.level = 1;
    }

    public void gainExperience(int points) {
        experiencePoints += points;
        System.out.println(getName() + " gains " + points + " experience points!");
        
        // Level up if enough experience is gained
        if (experiencePoints >= level * 100) {
            levelUp();
        }
    }
    
    private void levelUp() {
        level++;
        maxHealth += 10; // Increasing maximum health on level up
        health = maxHealth; // Full heal on level up
        System.out.println(getName() + " levels up to level " + level + "!");
    }

    public void printStatus() {
        System.out.println("Player: " + getName() + ", Level: " + level + 
                          ", Health: " + getHealth() + "/" + maxHealth + 
                          ", XP: " + experiencePoints);
    }
}
When Player calls super(playerName, initialHealth), it runs the Entity constructor to set up the parent class fields. Thanks to inheritance, you don’t need to duplicate the health variable or takeDamage() method in Player. You inherit them all from Entity, while adding player-specific behaviors like gaining experience and leveling up.

Subsection 8.6.2 Protected vs. Private

Java has three main access modifiers for fields and methods. We’ve already seen and used private (accessible only within the same class), public (accessible from any class). The third access modifier is protected which makes methods and fields accessible within the same class, subclasses, and classes in the same package.
In Java, a package is a way of organizing related classes and interfaces into a namespace to prevent naming conflicts and control access. It serves as a logical grouping mechanism, similar to folders in a file system. We’ve already been using packages when we import built-in Java classes (e.g., import java.util.ArrayList;) and external libraries. This allows us to access functionality without needing to define everything from scratch. To use a class from a different package, you must import it using the import statement or refer to it using its fully qualified name. Later, we will learn more about how to organize our own code into packages to improve maintainability and structure.
In the example above, health is declared protected. That means subclasses of Entity can access it directly. If health were private, then only the Entity class itself could access health, and subclasses would need methods like getHealth() to interact with it.
Use private fields when:
  • The field’s implementation might change in the future
  • You need to ensure validation when the field is modified
  • You want to maintain stricter encapsulation of internal state
Use protected fields when:
  • Subclasses legitimately need direct access to modify the field
  • The field’s implementation is stable and unlikely to change
  • Performance is critical and getter/setter overhead must be avoided

Insight 8.6.1. Best Practice for Field Access.

Default to private fields with accessor methods (getters/setters). This maintains better encapsulation and gives you more control over how fields are accessed and modified. Use protected sparingly and only when subclasses truly require direct field access for well-justified reasons.
Remember: You can always relax access restrictions later if needed, but tightening them may require significant refactoring.
Check Your Understanding

Checkpoint 8.6.2. Basic Inheritance Syntax.

Which keyword in Java indicates that one class is inheriting from another?
  • extends
  • Correct. The extends keyword establishes an inheritance relationship between classes.
  • implements
  • No, implements is used for interfaces, not class inheritance.
  • inherits
  • No, Java doesn’t have an inherits keyword.
  • super
  • No, super is used inside a subclass to call its superclass constructor or methods.

Checkpoint 8.6.3.

How do you declare that a class in Java inherits from another class?
  • class Subclass inherits Superclass {}
  • class Subclass extends Superclass {}
  • class Subclass implements Superclass {}
  • class Subclass includes Superclass {}

Checkpoint 8.6.4.

What happens if a subclass does not explicitly call a superclass constructor?
  • The compiler throws an error.
  • The default (no-argument) constructor of the superclass is automatically called.
  • The subclass must explicitly call super() in every constructor.
  • The superclass constructor is ignored.

Checkpoint 8.6.5.

What is the purpose of the super keyword in Java?
  • To create an instance of the superclass.
  • To access the private members of the superclass.
  • To call a constructor or method from the superclass.
  • To indicate that a method cannot be overridden.

Checkpoint 8.6.6.

What does the protected access modifier allow in Java?
  • Access only within the same class.
  • Access within the same class, subclasses, and the same package.
  • Access from any class in any package.
  • Access only in subclasses, even if they are in different packages.

Checkpoint 8.6.7.

What would happen if a field in a superclass is private?
  • It can still be directly accessed by subclasses.
  • It can only be accessed within the superclass itself.
  • Subclasses in the same package can access it without any restrictions.
  • It is automatically converted to protected when inherited.

Checkpoint 8.6.8.

What must you do to use a class from a different package in Java?
  • Define the class in the same file.
  • Copy and paste the class into your package.
  • Import the class using the import statement or use its fully qualified name.
  • Use the extends keyword to access the class directly.
You have attempted of activities on this page.