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:
| Parameter | Type | Description |
|---|---|---|
| extends | Keyword | Derives a subclass from a single superclass. |
| super() | Call | Invokes superclass constructor. |
Ready-to-Run Code Example
Executable in CompilraRun 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
Java Classes and Object-Oriented Programming (OOP)
Construct blueprints with constructors, private fields, getters, and setters.
Java Methods: Static Methods, Return Values, and Overloading
Learn how to declare methods, pass arguments, return values, and overload method signatures.
Java Exception Handling: try, catch, finally, and throws
Catch and throw checked and unchecked exceptions safely using try-catch-finally blocks.
Java Online Compiler
Open in Compilra IDE
Run and test Java on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.