Inheritance, polymorphism and overloading, step by step

Car

brandstart()brake()

Motorcycle

brandstart()brake()

Truck

brandstart()brake()

Copy and paste

A rule changes → you must touch three places

Inheritance

Vehicle brandstart()brake()

What is common lives once, on top; subclasses receive it with extends.

1 First statement

super(...)

Nothing runs before the inherited part is ready

2 If missing

super()

Java inserts it with no arguments, automatically

3 No empty constructor in the parent

does not compile

You must call one that does exist

Compile error

constructor Vehicle in class Vehicle cannot be applied to given types

By writing a constructor with arguments, Vehicle no longer has an empty one

super.start()

super.start(); // extends, does not replace

Calls the parent’s version of an overridden method

@Override

A compiler check

It changes nothing at runtime: it confirms you really override something

Without the annotation

start(int speed)

It is a new method of Car: the original stays inherited

Name and parameters

Identical: if they change, it is a new method

Return type

The same, or a subtype (covariant return)

Visibility

The same or wider, never narrower

Checked exceptions

The same, fewer, or subtypes

private · static · final

Cannot be overridden

Without polymorphism

if (v instanceof Car) { … } else if (v instanceof Motorcycle) { … } else if (v instanceof Truck) { … }

It grows forever and must be edited every time

With polymorphism

for (Vehicle v : fleet) v.start();

Each object runs its own version: no chain, no casts

Final class

public final class Coordinate

Nobody can inherit from this

Final method

public final void credit(…)

This method cannot be overridden

Overriding with other parameters

A new method. Always write @Override

Child constructor without super(...)

Call super(arguments) on the first line

Overridable method in the parent’s constructor

Use only private or final methods

Casting without instanceof

ClassCastException. Use if (v instanceof X x)

Inheriting just to reuse code

No "is-a": compose, hold the object and delegate

Mixing up overloading and overriding

Same class, different signatures vs. subclass, same signature

1 Step

Employee

name, baseSalary and computeSalary()

2 Step

Manager

adds a bonus via super.computeSalary()

3 Step

SalesRep

adds an 8% commission on its sales

4 Step

toString()

overridden in all three classes

5 Step

A single loop

over an Employee[]: no instanceof, no casts

1 · extends if an X is a Y2 · super(...) goes up, execution comes down3 · Always @Override4 · Overloading: compiler5 · Overriding: JVM6 · The variable defines what you call7 · Code that ignores the subclasses8 · Composition over inheritance

CursoDeJava · l10_herencia_polimorfismo_y_sobrecarga

Employees, zoo, transport, animals, people and subjects, and a library integrator