Java:Java Inheritance, Polymorphism, and the super Keyword
Java•Inheritance

Java Inheritance, Polymorphism, and the super Keyword

Learn subclassing in Java, polymorphic method dispatch, and accessing parent constructors via super().

Syntax

class SubClass extends SuperClass { @Override void method() { super.method(); } }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
extendsKeywordDerives a subclass from a single superclass.
super()CallInvokes superclass constructor.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Java locally:

class Employee {
    protected String name;
    protected double baseSalary;

    public Employee(String name, double baseSalary) {
        this.name = name;
        this.baseSalary = baseSalary;
    }

    public String getInfo() {
        return name + " ($" + (int)baseSalary + ")";
    }
}

class Developer extends Employee {
    private String primaryLang;

    public Developer(String name, double baseSalary, String primaryLang) {
        super(name, baseSalary); // Call parent constructor
        this.primaryLang = primaryLang;
    }

    @Override
    public String getInfo() {
        return super.getInfo() + " - Lead " + primaryLang + " Engineer";
    }
}

public class Main {
    public static void main(String[] args) {
        Employee emp = new Developer("Sarah", 125000, "Java");
        System.out.println(emp.getInfo());
    }
}
Expected Output:
Sarah ($125000) - Lead Java Engineer

How It Works: Step-by-Step

  • Lines 1-13: Base Employee class with protected fields and getInfo method.
  • Lines 15-28: Developer extends Employee and overrides getInfo with @Override.
  • Line 32: Polymorphic assignment: Developer instance held in Employee reference.

Key Concepts

  • Java supports single inheritance for classes (a class can extend only one superclass).
  • @Override annotation ensures the compiler checks that a method actually overrides a superclass method.
  • Polymorphism executes the subclass method at runtime even when referenced by parent type.

Common Mistake: Placing statements before super() in subclass constructor

super() must be the very first statement inside a subclass constructor.

❌ Incorrect
public Sub(int x) {
    System.out.println("init");
    super(x); // Compile Error: call to super must be first statement
}
✅ Correct
public Sub(int x) {
    super(x);
    System.out.println("init");
}

Related Java Tutorials & Compiler

Run and test Java on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Java Online Compiler