Classes that repeat themselves
A Car, a Motorcycle and a Truck share a brand, start() and brake(). Copy and paste works until a rule changes: then you must remember all three places.
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
CursoDeJava · l10_herencia_polimorfismo_y_sobrecarga
Employees, zoo, transport, animals, people and subjects, and a library integrator
A Car, a Motorcycle and a Truck share a brand, start() and brake().
Copy and paste works until a rule changes: then you must remember all three places.
A Car, a Motorcycle and a Truck share a brand, start() and brake(). Copy and paste works until a rule changes: then you must remember all three places.
Inheritance puts what is common on top, once, and every class receives it.
Polymorphism is its consequence: that is why the lesson covers both together.
Inheritance puts what is common on top, once, and every class receives it. Polymorphism is its consequence: that is why the lesson covers both together.
public class Vehicle {protected String brand; public Vehicle(String brand) { this.brand = brand; } public void start() { System.out.println("The vehicle starts."); }public void brake() { System.out.println("The vehicle brakes."); }} public class Car extends Vehicle {public Car(String brand) { super(brand); } @Overridepublic void start() {System.out.println("Car " + brand + " starting with a push button.");} public void openTrunk() { System.out.println("Trunk open."); }} extends makes Car receive every field and method of Vehicle.
The arrow points at the parent: it goes from the specific to the general.
extends makes Car receive every field and method of Vehicle. The arrow points at the parent: it goes from the specific to the general.
Car declares neither brand nor brake(), yet it has both: it inherited them.
Motorcycle and Truck get the same, and each class adds its own.
Car declares neither brand nor brake(), yet it has both: it inherited them. Motorcycle and Truck get the same, and each class adds its own.
A subclass can redefine an inherited method with @Override.
Car and Motorcycle change start(); Truck changes brake().
Everything else stays the parent’s.
A subclass can redefine an inherited method with @Override. Car and Motorcycle change start(); Truck changes brake(). Everything else stays the parent’s.
Before writing extends, ask yourself out loud: is an X a Y?
A Car is a Vehicle: the inheritance is right.
A Car is not an Engine: it has one. That is composition.
Before writing extends, ask yourself out loud: is an X a Y? A Car is a Vehicle: the inheritance is right. A Car is not an Engine: it has one. That is composition.
Java has single inheritance: a class extends exactly one class.
There is no extends A, B: interfaces exist to combine behaviors.
Java has single inheritance: a class extends exactly one class. There is no extends A, B: interfaces exist to combine behaviors.
Instantiating a subclass does not run one constructor: it runs the whole chain.
It goes from Object, the farthest ancestor, down to the concrete class.
Instantiating a subclass does not run one constructor: it runs the whole chain. It goes from Object, the farthest ancestor, down to the concrete class.
First the calls go up: each super(...) hands control to the parent.
If you do not write super(...), Java inserts super() on its own.
First the calls go up: each super(...) hands control to the parent. If you do not write super(...), Java inserts super() on its own.
Then the bodies run from the top down: 1, 2 and 3.
By the time the body of Car runs, the inherited part is fully initialized.
Then the bodies run from the top down: 1, 2 and 3. By the time the body of Car runs, the inherited part is fully initialized.
Three rules, no exceptions: super(...) must be the first statement.
If it is missing, Java inserts super(); and if the parent has none, it will not compile.
Three rules, no exceptions: super(...) must be the first statement. If it is missing, Java inserts super(); and if the parent has none, it will not compile.
The most common error: the parent only has a constructor with arguments.
The compiler complains about a constructor you never wrote.
Fix it by calling super(brand) on the first line.
The most common error: the parent only has a constructor with arguments. The compiler complains about a constructor you never wrote. Fix it by calling super(brand) on the first line.
public class Vehicle {protected String brand;public Vehicle(String brand) { this.brand = brand; }// By writing this constructor, Vehicle no longer has a no-arg one} public class Car extends Vehicle {public Car() {// ERROR: Java tries to insert super() and Vehicle has no such constructor}} javac Car.javaCar.java:8: error: constructor Vehicle in class Vehicle cannot be applied to given types; public Car() { ^ required: String found: no arguments super also calls the parent’s version of an overridden method.
That way you extend the behavior instead of replacing it.
super also calls the parent’s version of an overridden method. That way you extend the behavior instead of replacing it.
@Overridepublic void start() {super.start(); // first do what every vehicle doesSystem.out.println("...and engage keyless ignition.");} java MainThe vehicle starts....and engage keyless ignition. Overriding is redefining an inherited method with the same signature.
@Override changes nothing at runtime: it asks the compiler to verify it.
Without it, an extra parameter creates a new method and the bug is silent.
Overriding is redefining an inherited method with the same signature. @Override changes nothing at runtime: it asks the compiler to verify it. Without it, an extra parameter creates a new method and the bug is silent.
public class Car extends Vehicle {@Overridepublic void start(int speed) { // ← compile error, and that is a good thing...}} javac Car.javaCar.java:3: error: method does not override or implement a method from a supertype @Override ^ Name and parameters must be identical; the return may be a subtype.
Visibility may only widen, never narrow: it is the parent’s promise.
Checked exceptions never widen; private, static and final cannot be overridden.
Name and parameters must be identical; the return may be a subtype. Visibility may only widen, never narrow: it is the parent’s promise. Checked exceptions never widen; private, static and final cannot be overridden.
Overloading: several methods with the same name inside the same class.
The compiler picks by looking at the types of the arguments you wrote.
Everything is settled before running: no inheritance involved.
Overloading: several methods with the same name inside the same class. The compiler picks by looking at the types of the arguments you wrote. Everything is settled before running: no inheritance involved.
Overriding: one method redefined lower in the hierarchy.
The JVM decides, looking at the real object on the Heap.
It is only known once the program is running.
Overriding: one method redefined lower in the hierarchy. The JVM decides, looking at the real object on the Heap. It is only known once the program is running.
The return type does not count for overloading.
int compute() and double compute() do not compile together: which one to pick?
The return type does not count for overloading. int compute() and double compute() do not compile together: which one to pick?
A Vehicle variable can point at any object that is a Vehicle.
The variable lives on the Stack; the object, with its inherited layers, on the Heap.
A Vehicle variable can point at any object that is a Vehicle. The variable lives on the Stack; the object, with its inherited layers, on the Heap.
The variable’s type decides which methods you may write: the compiler checks it.
The object’s type decides which code runs: the JVM resolves it on every call.
Those two sentences are, literally, the definition of polymorphism.
The variable’s type decides which methods you may write: the compiler checks it. The object’s type decides which code runs: the JVM resolves it on every call. Those two sentences are, literally, the definition of polymorphism.
v.start(): the compiler checks that Vehicle declares start().
At runtime the JVM follows the reference and looks for the method in the real object.
It starts at Car: the overridden version is there, and that is the one that runs.
v.start(): the compiler checks that Vehicle declares start(). At runtime the JVM follows the reference and looks for the method in the real object. It starts at Car: the overridden version is there, and that is the one that runs.
v.brake(): Car did not override it, so the search keeps going up.
It finds it in Vehicle and runs that inherited version.
v.brake(): Car did not override it, so the search keeps going up. It finds it in Vehicle and runs that inherited version.
v.openTrunk() does not compile: Vehicle does not declare openTrunk().
To use what is specific to Car you need a cast, with a safety net: instanceof.
Without the check, a wrong cast blows up with ClassCastException.
v.openTrunk() does not compile: Vehicle does not declare openTrunk(). To use what is specific to Car you need a cast, with a safety net: instanceof. Without the check, a wrong cast blows up with ClassCastException.
A Vehicle array holds a Car, a Motorcycle and a Truck at once.
Each cell points at a different object, but all of them are of type Vehicle.
A Vehicle array holds a Car, a Motorcycle and a Truck at once. Each cell points at a different object, but all of them are of type Vehicle.
Garage.inspect walks the fleet without knowing which class sits in each cell.
Each object runs ITS own version of start().
It is a single loop: no instanceof and no casts.
Garage.inspect walks the fleet without knowing which class sits in each cell. Each object runs ITS own version of start(). It is a single loop: no instanceof and no casts.
Tomorrow you add Bicycle extends Vehicle and the Garage handles it unchanged.
That is the payoff: new code that plugs in without touching code that already worked.
Tomorrow you add Bicycle extends Vehicle and the Garage handles it unchanged. That is the payoff: new code that plugs in without touching code that already worked.
Without polymorphism you need an instanceof chain that grows forever.
And you must edit it every time a new class appears.
With polymorphism each class knows what to do and the loop never changes.
Without polymorphism you need an instanceof chain that grows forever. And you must edit it every time a new class appears. With polymorphism each class knows what to do and the loop never changes.
public class Garage {// This method knows nothing about Car, Motorcycle, or Truck. It does not need to.public void inspect(Vehicle[] fleet) {for (Vehicle v : fleet) {v.start(); // each object runs ITS own versionv.brake();}}} Vehicle[] fleet = {new Car("Toyota"),new Motorcycle("Honda"),new Truck("Scania")};new Garage().inspect(fleet); Inheritance is the strongest relationship between two classes: it ties the subclass to the parent.
Car extends Engine fails the test: a Car is not an Engine.
Inheritance is the strongest relationship between two classes: it ties the subclass to the parent. Car extends Engine fails the test: a Car is not an Engine.
Composition: a Car has an Engine and delegates the work to it.
engine.ignite(): the Car inherits nothing, it just asks the engine.
Composition: a Car has an Engine and delegates the work to it. engine.ignite(): the Car inherits nothing, it just asks the engine.
You can swap the engine without touching a single line of Car.
And test the Car with a fake engine. Inheritance allows neither.
You can swap the engine without touching a single line of Car. And test the Car with a fake engine. Inheritance allows neither.
If a class must not be extended, mark it final and the compiler enforces it.
The same goes for a method: a final one cannot be overridden.
If a class must not be extended, mark it final and the compiler enforces it. The same goes for a method: a final one cannot be overridden.
public final class Coordinate { ... } // nobody can inherit from this public class Account {public final void credit(double amount) { ... } // this method cannot be overridden} Even if you never write extends, every Java class inherits from Object.
That is where methods you used without noticing come from: toString(), equals() and hashCode().
Even if you never write extends, every Java class inherits from Object. That is where methods you used without noticing come from: toString(), equals() and hashCode().
Without overriding toString(), println(a) prints the class and a hash code.
The search climbs up to Object and runs its version: useless for debugging.
Without overriding toString(), println(a) prints the class and a hash code. The search climbs up to Object and runs its version: useless for debugging.
Overriding it costs two lines and gives you back hours of debugging.
Now the search stops at Car and the result is readable.
equals() and hashCode() have rules of their own: you will see them in lesson 16.
Overriding it costs two lines and gives you back hours of debugging. Now the search stops at Car and the result is readable. equals() and hashCode() have rules of their own: you will see them in lesson 16.
Overriding while changing the parameters creates a new method: always write @Override.
A child constructor without super(...) fails if the parent has no empty constructor.
Calling an overridable method from the parent’s constructor leaves fields uninitialized.
Overriding while changing the parameters creates a new method: always write @Override. A child constructor without super(...) fails if the parent has no empty constructor. Calling an overridable method from the parent’s constructor leaves fields uninitialized.
Casting without instanceof ends in ClassCastException at runtime.
Inheriting just to reuse code, with no "is-a", builds rigid hierarchies: compose instead.
And do not mix up overloading and overriding: one is the compiler’s, the other the JVM’s.
Casting without instanceof ends in ClassCastException at runtime. Inheriting just to reuse code, with no "is-a", builds rigid hierarchies: compose instead. And do not mix up overloading and overriding: one is the compiler’s, the other the JVM’s.
The challenge: an employee hierarchy with Employee, Manager and SalesRep.
Each subclass overrides computeSalary() and all three override toString().
The challenge: an employee hierarchy with Employee, Manager and SalesRep. Each subclass overrides computeSalary() and all three override toString().
Manager adds a bonus and SalesRep an 8% commission, both through super.computeSalary().
They do not repeat the base salary logic: they reuse it and add their own.
Manager adds a bonus and SalesRep an 8% commission, both through super.computeSalary(). They do not repeat the base salary logic: they reuse it and add their own.
public class Employee {private final String name;private final double baseSalary; public Employee(String name, double baseSalary) {this.name = name;this.baseSalary = baseSalary;} public double computeSalary() { return baseSalary; } @Overridepublic String toString() { return getClass().getSimpleName() + " " + name; }} public class Manager extends Employee {private final double bonus; public Manager(String name, double baseSalary, double bonus) {super(name, baseSalary); // first statement, mandatorythis.bonus = bonus;} @Overridepublic double computeSalary() {return super.computeSalary() + bonus; // extends, does not replace}} public class SalesRep extends Employee {private static final double COMMISSION = 0.08; // 8 % commissionprivate final double monthlySales; public SalesRep(String name, double baseSalary, double monthlySales) {super(name, baseSalary);this.monthlySales = monthlySales;} @Overridepublic double computeSalary() {return super.computeSalary() + monthlySales * COMMISSION;}} What matters is the loop: it never asks which type each employee is.
If you add an Intern tomorrow, that loop keeps working without a single change.
What matters is the loop: it never asks which type each employee is. If you add an Intern tomorrow, that loop keeps working without a single change.
Employee[] payroll = {new Employee("Ana Torres", 800000),new Manager("Luis Paz", 1500000, 400000),new SalesRep("Sofia Rios", 700000, 2500000)}; double total = 0;// A single loop, no instanceof and no casts:for (Employee e : payroll) {double salary = e.computeSalary();total += salary;System.out.printf("%-22s $ %,.2f%n", e, salary);}System.out.printf("%-22s $ %,.2f%n", "TOTAL", total); java MainPayrollEmployee Ana Torres $ 800,000.00Manager Luis Paz $ 1,900,000.00SalesRep Sofia Rios $ 900,000.00TOTAL $ 3,600,000.00 extends only if an X is a Y; the constructor chain goes up with super and runs downwards.
Overloading is the compiler’s call, overriding the JVM’s: the variable defines what you may call.
Prefer composition over inheritance, and mark with final whatever must not be extended.
extends only if an X is a Y; the constructor chain goes up with super and runs downwards. Overloading is the compiler’s call, overriding the JVM’s: the variable defines what you may call. Prefer composition over inheritance, and mark with final whatever must not be extended.
Reinforce everything with complete programs in the course repository.
Clone it, open l10_herencia_polimorfismo_y_sobrecarga and run each one while you reread the lesson.
Reinforce everything with complete programs in the course repository. Clone it, open l10_herencia_polimorfismo_y_sobrecarga and run each one while you reread the lesson.