Java tutorialLesson 17 of 18 · tap to see all lessons
Java tutorial · Intermediate
Java Inheritance, Polymorphism, Abstract Classes, and Interfaces
Reuse code with extends and super, override methods, use compile-time and runtime polymorphism with up- and downcasting, and design with abstract classes and interfaces.
- Qyubie Learn Editorial Team
- Published
- 18 min read
Includes 4 quick checks you can do right here.
A school has students, instructors, and staff. All of them have a name, an ID, and contact details, but each also has things of its own: a student has a course, an instructor has a department. Writing those shared fields three times means fixing every bug three times. Inheritance lets the shared part live in one class that the others build on, and polymorphism lets one piece of code work with all of them. Together with abstraction, these complete the four pillars of OOP you met in lesson 9.
By the end of this lesson you will be able to:
- create subclasses with
extendsand usesuper, - override methods and explain dynamic method dispatch,
- tell compile-time polymorphism from runtime polymorphism, and use up- and downcasting safely, and
- write abstract classes and interfaces, and choose between them.
Inheritance with extends
A subclass (child) extends a superclass (parent). It inherits the parent's fields and methods, and adds its own:
class Person {
protected String name;
Person(String name) {
this.name = name;
}
void introduce() {
System.out.println("Hi, I'm " + name + ".");
}
}
class Student extends Person {
private String course;
Student(String name, String course) {
super(name); // run Person's constructor first
this.course = course;
}
void study() {
System.out.println(name + " is studying " + course + ".");
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student("Ana", "BSCS");
s.introduce(); // inherited from Person
s.study(); // Student's own method
}
}Output:
Hi, I'm Ana.
Ana is studying BSCS.Studentnever declaresnameorintroduce(); it inherits them. That's the is-a relationship from lesson 13: a Student is a Person.protected(lesson 12) lets the subclass usenamedirectly while keeping it hidden from unrelated classes.- Java allows one parent per class:
class A extends B, Cis an error. A parent can have any number of children, though. - Every class that doesn't say
extendsautomatically extendsObject, Java's root class. That's wheretoString()andequals()come from.
The super keyword
super refers to the parent part of the object. It has two uses:
super(...)calls the parent's constructor. It must be the first line of the subclass constructor. If you leave it out, Java insertssuper()with no arguments, which fails to compile when the parent has no no-argument constructor.super.method()calls the parent's version of a method, usually from inside an override, to extend its behavior rather than replace it.
class Person {
protected String name;
Person(String name) {
this.name = name;
System.out.println("Person constructor");
}
String describe() {
return "Name: " + name;
}
}
class Instructor extends Person {
private String department;
Instructor(String name, String department) {
super(name);
this.department = department;
System.out.println("Instructor constructor");
}
@Override
String describe() {
return super.describe() + ", Dept: " + department; // reuse the parent's text
}
}
public class Main {
public static void main(String[] args) {
Instructor i = new Instructor("Mr. Santos", "Computer Science");
System.out.println(i.describe());
}
}Output:
Person constructor
Instructor constructor
Name: Mr. Santos, Dept: Computer ScienceThe parent's constructor always runs before the child's, because a child is built on top of a finished parent.
Method overriding
A subclass can give its own version of an inherited method. This is overriding: same name, same parameters, same (or compatible) return type.
class Shape {
double area() {
return 0;
}
}
class Circle extends Shape {
private double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
private double width, height;
Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
double area() {
return width * height;
}
}
public class Main {
public static void main(String[] args) {
System.out.printf("%.2f%n", new Circle(1).area());
System.out.printf("%.2f%n", new Rectangle(3, 4).area());
}
}Output:
3.14
12.00@Override is optional, but always write it. It asks the compiler to check that you really are overriding something. If you misspell the name (Area()) or change the parameters, you get a compile error instead of a silent new method.
Overriding vs. overloading, side by side:
| Overloading (lesson 13) | Overriding | |
|---|---|---|
| Where | same class | parent and child class |
| Parameters | must differ | must be the same |
| Decided | at compile time | at run time |
| Purpose | same idea for different inputs | a child's own version of a parent's behavior |
Quick check
Polymorphism and dynamic dispatch
Polymorphism means "many forms": one variable or method call that works with objects of different classes.
A parent-type variable can hold any subclass object. When you call an overridden method on it, Java looks at the actual object at run time and runs its version. This is dynamic method dispatch:
class Shape {
String name() { return "shape"; }
double area() { return 0; }
}
class Circle extends Shape {
private double r;
Circle(double r) { this.r = r; }
@Override String name() { return "circle"; }
@Override double area() { return Math.PI * r * r; }
}
class Square extends Shape {
private double side;
Square(double side) { this.side = side; }
@Override String name() { return "square"; }
@Override double area() { return side * side; }
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Circle(2), new Square(3), new Circle(1) };
double total = 0;
for (Shape s : shapes) {
System.out.printf("%-6s %6.2f%n", s.name(), s.area()); // which area()? decided at run time
total += s.area();
}
System.out.printf("Total %6.2f%n", total);
}
}Output:
circle 12.57
square 9.00
circle 3.14
Total 24.71The loop doesn't know or care which shapes it has. Add a Triangle class tomorrow, and this loop works with it without changing a line. That's the real payoff of polymorphism: code written for the parent type keeps working as new subclasses appear.
Java has two kinds of polymorphism:
- Compile-time (static) polymorphism is overloading. The compiler picks the method from the argument types, before the program runs.
- Runtime (dynamic) polymorphism is overriding. The JVM picks the method from the actual object, while the program runs.
Upcasting and downcasting
Storing a subclass object in a parent-type variable is upcasting. It's automatic and always safe, because a Circle is a Shape:
Shape s = new Circle(2); // upcast: automaticBut through a Shape variable you can only call methods that Shape declares. The variable's type decides what you may call; the object's type decides which version runs.
To use a method that only the subclass has, you downcast back. Downcasting needs an explicit cast, and it's only safe if the object really is that type, so check first with instanceof:
class Shape {
double area() { return 0; }
}
class Circle extends Shape {
double r;
Circle(double r) { this.r = r; }
@Override double area() { return Math.PI * r * r; }
double diameter() { return 2 * r; }
}
class Square extends Shape {
double side;
Square(double side) { this.side = side; }
@Override double area() { return side * side; }
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Circle(5), new Square(2) };
for (Shape s : shapes) {
// s.diameter(); // error: Shape has no diameter()
if (s instanceof Circle) {
Circle c = (Circle) s; // downcast, now known to be safe
System.out.println("Circle, diameter " + c.diameter());
} else {
System.out.println("Not a circle, area " + s.area());
}
}
}
}Output:
Circle, diameter 10.0
Not a circle, area 4.0Without the instanceof check, (Circle) s on a Square compiles but throws a ClassCastException at run time. Since Java 16 you can test and cast in one step: if (s instanceof Circle c) { ... c.diameter() ... }.
Quick check
Abstract classes
In the shape examples, Shape.area() returned 0, which is meaningless. There's no such thing as a plain "shape"; every real shape is a circle, a square, and so on. An abstract class expresses that:
- It's declared
abstractand can't be instantiated withnew. - It can have abstract methods: a signature with no body, which every concrete subclass must override.
- It can still have fields, constructors, and normal methods that subclasses inherit.
abstract class Employee {
private String name;
Employee(String name) {
this.name = name;
}
String getName() {
return name;
}
abstract double monthlyPay(); // no body: each kind computes it differently
void printPayslip() { // a normal method that uses the abstract one
System.out.printf("%-6s %,10.2f%n", name, monthlyPay());
}
}
class FullTime extends Employee {
private double salary;
FullTime(String name, double salary) {
super(name);
this.salary = salary;
}
@Override
double monthlyPay() {
return salary;
}
}
class PartTime extends Employee {
private double hourlyRate;
private int hours;
PartTime(String name, double hourlyRate, int hours) {
super(name);
this.hourlyRate = hourlyRate;
this.hours = hours;
}
@Override
double monthlyPay() {
return hourlyRate * hours;
}
}
public class Main {
public static void main(String[] args) {
Employee[] staff = { new FullTime("Ana", 30000), new PartTime("Ben", 250, 64) };
for (Employee e : staff) {
e.printPayslip();
}
// Employee x = new Employee("Cara"); // error: Employee is abstract; cannot be instantiated
}
}Output:
Ana 30,000.00
Ben 16,000.00printPayslip() is written once in Employee, but each call to monthlyPay() inside it runs the subclass's version. If a new subclass forgets to write monthlyPay(), it won't compile, so the mistake is caught early. (A subclass that doesn't implement every abstract method must itself be declared abstract.)
Interfaces
An interface is a pure contract: a list of methods a class promises to provide. A class implements it:
interface Payable {
double amountDue(); // public and abstract automatically
}
interface Printable {
void print();
}
class Invoice implements Payable, Printable {
private String item;
private int quantity;
private double unitPrice;
Invoice(String item, int quantity, double unitPrice) {
this.item = item;
this.quantity = quantity;
this.unitPrice = unitPrice;
}
@Override
public double amountDue() {
return quantity * unitPrice;
}
@Override
public void print() {
System.out.printf("Invoice: %d x %s = %.2f%n", quantity, item, amountDue());
}
}
class Tuition implements Payable {
private int units;
Tuition(int units) {
this.units = units;
}
@Override
public double amountDue() {
return units * 500.0;
}
}
public class Main {
public static void main(String[] args) {
Payable[] bills = { new Invoice("Ream of paper", 2, 250), new Tuition(21) };
double total = 0;
for (Payable p : bills) {
total += p.amountDue();
}
System.out.printf("Total due: %.2f%n", total);
new Invoice("Ballpen", 10, 12.5).print();
}
}Output:
Total due: 11000.00
Invoice: 10 x Ballpen = 125.00Key points:
- Interface methods are
publicandabstractby default, so the implementing methods must bepublic. - A class can implement many interfaces (
implements Payable, Printable), even though it can extend only one class. That's how Java gets the benefit of multiple inheritance without its problems. - Unrelated classes, here an
Invoiceand aTuitionfee, can share an interface and be used together through it. - Interfaces can also hold constants and, since Java 8,
defaultmethods with a body, but the main idea is the contract.
Abstract class or interface?
| Abstract class | Interface | |
|---|---|---|
| Keyword | abstract class, used with extends | interface, used with implements |
| How many per class | one | many |
| Fields | any fields, including instance fields | constants only (static final) |
| Constructors | yes | no |
| Methods | abstract and normal methods | abstract, plus default and static methods |
| Relationship | is-a: a FullTime is an Employee | can-do: an Invoice can be paid |
| Use when | closely related classes share code and state | unrelated classes share a capability |
A common design uses both: an abstract class for the shared code of a family, and interfaces for abilities that cut across families.
Quick check
Quick check
Common mistakes
- Using inheritance for has-a.
class Car extends Engineis wrong: a car has an engine. Use a field. - Forgetting
super(...)when the parent has no no-argument constructor: constructor Person in class Person cannot be applied to given types. - Changing the parameters when you meant to override, which creates an overload instead.
@Overridecatches this. - Downcasting without
instanceof, which risks aClassCastException. - Making interface methods non-public in the implementing class: attempting to assign weaker access privileges.
- Trying to
newan abstract class or an interface.
Summary
class Child extends Parentinherits fields and methods (is-a).super(...)calls the parent's constructor first;super.method()calls the parent's version.- Overriding gives a subclass its own version of a method;
@Overridechecks it. - Polymorphism: a parent-type reference can hold any subclass object, and dynamic dispatch runs the object's own method. Overloading is compile-time polymorphism; overriding is runtime polymorphism.
- Upcasting is automatic; downcasting needs a cast and an
instanceofcheck. - An abstract class can't be instantiated and may force subclasses to write certain methods; an interface is a contract that any class can implement, many at a time.
Next lesson: exception handling and collections: handling errors gracefully, and storing objects in ArrayList and HashMap.