It compiles, but a “generic vehicle” does not exist
Problem 2
Vehicle.start()
A body invented just so it compiles
Abstract class
An incomplete mold
Brings state and solved behavior, and leaves gaps
Interface
A pure contract
Says what whoever signs it must be able to do
State
protected final String name;
Fields and a constructor, like any class
Gap
public abstract double area();
No body: the subclass must write it
Solved
public void describe()
Has a body: inherited as is
Cannot be instantiated · a class extends ONE only
Constant
int MAX_LAYERS = 10;
public static final
Abstract
void draw();
Public and abstract by default
default
default void highlight()
Inheritable implementation (Java 8+)
static
static Drawable empty()
A utility of the interface itself
No instance state · implement as many as you want
Before Java 8
Adding a method broke everything
The thousand classes already implementing it stopped compiling
default
A method with a body
Classes inherit it and may override it or not
Sparingly
Not a disguised abstract class
default is for evolving a contract, not for writing logic
static
Payable.isValidAmount(500)
Not inherited: called through the interface
Adapter class
WindowListener → WindowAdapter
Seven empty methods already written: you override just one
extends
Bird
A single line of inheritance
implements
Swimmer, Flyer
As many contracts as needed
The same object, several angles
Bird b = duckSwimmer s = duckFlyer f = duck
CriterionAbstract classInterface
Relationship it expresses
“is a”: shared identity
“is capable of”: shared capability
How many you can use
Only one (extends)
As many as you want (implements)
Instance state
Yes, ordinary fields
No, only static final constants
Constructors
Yes
No
Method visibility
Anything, including protected
Always public
Adding a method later
Breaks subclasses if abstract
Breaks nothing if default
Interface by default. Abstract class only with shared state or code.
namespace
A container that gives every type a unique context
Stops two classes with the same name from competing in one global scope
1 package
package com.facundouferer.shop;
Defines the namespace of the whole file
2 FQCN
com.facundouferer.shop.domain.Product
The real identity of the class for the JVM
3 import
import ...shop.domain.Product;
A lexical shortcut: it loads no bytecode
Reversed domain: com.facundoufererAll lowercaseOne .java per public classGroup by responsibilityStatic imports, sparinglypackage-private: a trust boundary
Association
Teacher → Course
They know each other, neither owns the other
Aggregation
Team ◇ Player
Receives the parts from outside
Composition
House ◆ Room
Creates the parts and does not expose them
Abstract class where an interface belongsA default on every methodMutable fields in an interfacePackage that does not match the folderName collision when importingAggregation that was compositionOne giant package
1 Step
Payable
pay · isAvailable · default payIfPossible
2 Step
CreditCard · DigitalWallet
implements Payable
3 Step
DigitalPaymentMethod
Abstract class: email + active
4 Step
DigitalWallet extends
Reuses super.isAvailable()
5 Step
Payable[]
One loop, no instanceof and no casting
1 · Abstract class: incomplete mold2 · Interface: pure contract3 · Interface first4 · default: evolve without breaking5 · Extends one, implements many6 · package = namespace · FQCN7 · If I destroy the whole, does the part exist?
In the previous lesson, Vehicle had a quiet problem: nothing stops you from writing new Vehicle("Ford").
A generic vehicle does not exist in the real world: it is a concept, not a thing.
And start() invented a body no subclass uses, just so it would compile.
A vehicle that does not exist
In the previous lesson, Vehicle had a quiet problem: nothing stops you from writing new Vehicle("Ford"). A generic vehicle does not exist in the real world: it is a concept, not a thing. And start() invented a body no subclass uses, just so it would compile.
Java has two tools to fix it, and choosing badly is a decision you pay for a long time.
The abstract class is an incomplete mold; the interface is a pure contract.
Two tools
Java has two tools to fix it, and choosing badly is a decision you pay for a long time. The abstract class is an incomplete mold; the interface is a pure contract.
An abstract class cannot be instantiated: it exists only to be extended.
It can have state and a constructor, concrete methods and abstract methods with no body.
Look at describe(): it calls two methods that do not exist yet.
Anatomy of an abstract class
An abstract class cannot be instantiated: it exists only to be extended. It can have state and a constructor, concrete methods and abstract methods with no body. Look at describe(): it calls two methods that do not exist yet.
Shape.javajava
publicabstractclassShape{protectedfinalString name;protectedShape(String name){this.name = name;}// No body: every subclass MUST write thempublicabstractdoublearea();publicabstractdoubleperimeter();// Has a body: inherited as ispublicvoiddescribe(){System.out.printf("%s → area %.2f, perimeter %.2f%n",name,area(),perimeter());}}
An abstract class is an incomplete mold: it brings state and leaves gaps.
Abstract methods have no body: they force each subclass to write them.
Concrete ones, like describe(), are already solved and inherited as is.
A mold with gaps
An abstract class is an incomplete mold: it brings state and leaves gaps. Abstract methods have no body: they force each subclass to write them. Concrete ones, like describe(), are already solved and inherited as is.
describe() calls two methods that do not exist yet.
The abstract class writes the algorithm once and delegates the concrete steps.
An algorithm with delegated steps
describe() calls two methods that do not exist yet. The abstract class writes the algorithm once and delegates the concrete steps.
And new Shape(...) does not even compile: the compiler stops the object that made no sense.
An abstract class exists only to be extended.
new Shape() does not compile
And new Shape(...) does not even compile: the compiler stops the object that made no sense. An abstract class exists only to be extended.
Circle and Rectangle extend Shape and fill every gap with their own formula.
If a subclass leaves a gap unfilled, it must be declared abstract too.
Subclasses fill the gaps
Circle and Rectangle extend Shape and fill every gap with their own formula. If a subclass leaves a gap unfilled, it must be declared abstract too.
With the mold fixed, each subclass only contributes its own part.
A Shape[] holding circles and rectangles calls describe() without telling them apart.
Concrete subclasses at work
With the mold fixed, each subclass only contributes its own part. A Shape[] holding circles and rectangles calls describe() without telling them apart.
javac Main.javaerror: Shape is abstract; cannot be instantiated// we remove that line and compile againjava MainCircle → area 28.27, perimeter 18.85Rectangle → area 20.00, perimeter 18.00
An interface describes what can be done, never how.
Its methods are public abstract without writing it, and it holds no instance state.
A pure contract
An interface describes what can be done, never how. Its methods are public abstract without writing it, and it holds no instance state.
Payable.javajava
publicinterfacePayable{// Every method is public abstract by defaultbooleanpay(double amount);booleanisAvailable();}
An interface is a pure contract: it says what can be done, never how.
Every method is public abstract by default: there is no need to write it.
And with default the contract can carry an implementation classes inherit.
The clauses of the contract
An interface is a pure contract: it says what can be done, never how. Every method is public abstract by default: there is no need to write it. And with default the contract can carry an implementation classes inherit.
Any class signs the contract with implements, and the compiler forces it to honor all of it.
CreditCard inherits from nobody: the interface does not use up your only extends.
DigitalWallet already extends an abstract class and still signs the same contract.
Three classes sign with implements
Any class signs the contract with implements, and the compiler forces it to honor all of it. CreditCard inherits from nobody: the interface does not use up your only extends. DigitalWallet already extends an abstract class and still signs the same contract.
A Payable[] holds all three, with no instanceof and no casting.
When payIfPossible(12500) is called, each one answers in its own way.
The third method has no balance: the contract skips it.
A single loop for all of them
A Payable[] holds all three, with no instanceof and no casting. When payIfPossible(12500) is called, each one answers in its own way. The third method has no balance: the contract skips it.
@Override marks each contract method that CreditCard honors.
The class inherits from nobody: it only signs Payable and writes what it promises.
CreditCard honors the contract
@Override marks each contract method that CreditCard honors. The class inherits from nobody: it only signs Payable and writes what it promises.
Since Java 8, an interface can carry implementations with default.
They exist to add a method without breaking the thousand classes already implementing it.
Use them sparingly: an interface full of defaults is a badly disguised abstract class.
Default methods
Since Java 8, an interface can carry implementations with default. They exist to add a method without breaking the thousand classes already implementing it. Use them sparingly: an interface full of defaults is a badly disguised abstract class.
Payable.javajava
publicinterfacePayable{booleanpay(double amount);booleanisAvailable();// default: inheritable implementationdefaultvoidpayIfPossible(double amount){if(isAvailable()){pay(amount);}else{System.out.println("Payment method unavailable.");}}// static: a utility of the interface itselfstaticbooleanisValidAmount(double amount){return amount >0&& amount <1_000_000;}}
The static methods of an interface are not inherited.
They are always called through the interface name, never from an instance or from the class.
static is not inherited
The static methods of an interface are not inherited. They are always called through the interface name, never from an instance or from the class.
UsoStatic.javajava
Payable.isValidAmount(500);// ✓ through the interfacecard.isValidAmount(500);// ✗ does not compileCreditCard.isValidAmount(500);// ✗ neither does this
If an interface is long and you care about one method, implementing it fully fills the code with empty methods.
An adapter class implements it empty and you override only what you need.
The trade-off: being a class, it uses up your only inheritance.
Adapter classes
If an interface is long and you care about one method, implementing it fully fills the code with empty methods. An adapter class implements it empty and you override only what you need. The trade-off: being a class, it uses up your only inheritance.
WindowEvents.javajava
classWindowEventsextendsWindowAdapter{@OverridepublicvoidwindowActivated(WindowEvent e){System.out.println("WINDOW ACTIVE");}}// addWindowListener expects a WindowListener:// a WindowAdapter is onemyFrame.addWindowListener(newWindowEvents());
A class extends a single class, but implements every interface it needs.
Java has no multiple class inheritance: the answer is contracts.
One inheritance, many contracts
A class extends a single class, but implements every interface it needs. Java has no multiple class inheritance: the answer is contracts.
Duck extends Bird, its single line of inheritance, and implements Swimmer and Flyer.
It inherits eat() and writes swim() and fly().
Duck extends and implements
Duck extends Bird, its single line of inheritance, and implements Swimmer and Flyer. It inherits eat() and writes swim() and fly().
The same object can be seen from different angles.
As a Bird, a Swimmer or a Flyer, depending on what each method needs.
The same object, three angles
The same object can be seen from different angles. As a Bird, a Swimmer or a Flyer, depending on what each method needs.
A Swimmer[] can hold a Duck, a Fish and a Submarine.
Three classes with no common ancestor: the interface is all they share, and it is enough.
Three classes with no common ancestor
A Swimmer[] can hold a Duck, a Fish and a Submarine. Three classes with no common ancestor: the interface is all they share, and it is enough.
One line of inheritance and many contracts: that is Java’s answer to multiple inheritance.
A method that only needs something to swim has no reason to know it is a duck.
Duck in code
One line of inheritance and many contracts: that is Java’s answer to multiple inheritance. A method that only needs something to swim has no reason to know it is a duck.
Duck.javajava
publicclassDuckextendsBirdimplementsSwimmer,Flyer{@Overridepublicvoidswim(){System.out.println("The duck swims.");}@Overridepublicvoidfly(){System.out.println("The duck flies.");}}Duck duck =newDuck();Bird b = duck;// as a birdSwimmer s = duck;// as something that swimsFlyer f = duck;// as something that fliespublicvoidswimmingContest(Swimmer[] participants){for(Swimmer participant : participants){participant.swim();}}
The abstract class expresses “is a”: a shared identity.
The interface expresses “is capable of”: a capability anyone can sign.
A class extends only one; it implements as many interfaces as it wants.
Identity or capability
The abstract class expresses “is a”: a shared identity. The interface expresses “is capable of”: a capability anyone can sign. A class extends only one; it implements as many interfaces as it wants.
Only the abstract class has instance state and constructors.
Adding an abstract method breaks subclasses; a default one breaks nothing.
State, visibility and evolution
Only the abstract class has instance state and constructors. Adding an abstract method breaks subclasses; a default one breaks nothing.
The rule that holds in 90% of cases: interface by default.
Abstract class only when there is shared state or code you do not want to repeat.
The practical rule
The rule that holds in 90% of cases: interface by default. Abstract class only when there is shared state or code you do not want to repeat.
The two combine: the interface sets the contract and the abstract class solves the repetitive part.
findById() is already solved; save() stays abstract.
Each concrete subclass decides what to validate before saving.
Interface plus abstract base
The two combine: the interface sets the contract and the abstract class solves the repetitive part. findById() is already solved; save() stays abstract. Each concrete subclass decides what to validate before saving.
Interface by default. Abstract class only when there is shared state or code.
Interface first
Interface by default. Abstract class only when there is shared state or code.
A namespace groups types and gives them a unique context to prevent name collisions.
Java has no namespace keyword: it uses package.
What a namespace is
A namespace groups types and gives them a unique context to prevent name collisions. Java has no namespace keyword: it uses package.
Three pillars: the package declaration, the FQCN, and import as a shortcut.
The folder must match the package, always: otherwise it does not compile.
Three pillars
Three pillars: the package declaration, the FQCN, and import as a shortcut. The folder must match the package, always: otherwise it does not compile.
Product.javajava
package com.facundouferer.shop.domain;// first line, mandatorypublicclassProduct{...}
Terminalbash
tree srcsrc└── com/facundouferer/shop ├── domain/Product.java ├── service/CartService.java └── Main.java
To the JVM, a class’s identity is its fully qualified name, the FQCN.
That is why two Product classes coexist without ambiguity in the same application.
Two Product, zero ambiguity
To the JVM, a class’s identity is its fully qualified name, the FQCN. That is why two Product classes coexist without ambiguity in the same application.
import loads nothing: it only registers an alias so you type less.
Two classes with the same short name cannot be imported together.
Collision when importing
import loads nothing: it only registers an alias so you type less. Two classes with the same short name cannot be imported together.
The fix: import the one you use most and write the FQCN of the other.
Every name is unambiguous and the compiler knows which one you mean.
Disambiguate with the FQCN
The fix: import the one you use most and write the FQCN of the other. Every name is unambiguous and the compiler knows which one you mean.
Reversed domain, all lowercase, and one file per public class.
Group by responsibility, not by artifact type: domain and service, not interfaces.
And package-private access turns the package into a trust boundary.
Package design rules
Reversed domain, all lowercase, and one file per public class. Group by responsibility, not by artifact type: domain and service, not interfaces. And package-private access turns the package into a trust boundary.
Association: objects know each other and collaborate, but each lives on its own.
A Teacher keeps its Course objects, and neither owns the other.
Association
Association: objects know each other and collaborate, but each lives on its own. A Teacher keeps its Course objects, and neither owns the other.
Aggregation: the whole gathers parts that already existed and receives them from outside.
A Team receives its Player objects in the constructor, with a defensive copy.
Aggregation
Aggregation: the whole gathers parts that already existed and receives them from outside. A Team receives its Player objects in the constructor, with a defensive copy.
Composition: the part cannot exist without the whole, which creates it in its constructor.
House creates its Room objects and has no getRooms(): nobody outside touches them.
Composition
Composition: the part cannot exist without the whole, which creates it in its constructor. House creates its Room objects and has no getRooms(): nobody outside touches them.
The question that decides it: if I destroy the container, does the part still make sense?
Association and aggregation: the part survives. Composition: it goes with the whole.
If I destroy the whole…
The question that decides it: if I destroy the container, does the part still make sense? Association and aggregation: the part survives. Composition: it goes with the whole.
In aggregation, the container receives the parts from outside.
That is why it makes a defensive copy with Arrays.copyOf: the original array belongs to someone else.
Aggregation in code
In aggregation, the container receives the parts from outside. That is why it makes a defensive copy with Arrays.copyOf: the original array belongs to someone else.
Relaciones.javajava
// ASSOCIATION: they know each other, neither owns the otherpublicclassTeacher{privateCourse[] courses =newCourse[10];}// AGGREGATION: receives the parts from outsidepublicclassTeam{privatefinalPlayer[] players;publicTeam(Player[] players){this.players =Arrays.copyOf(players, players.length);}}// COMPOSITION: creates its parts and does not expose thempublicclassHouse{privatefinalRoom[] rooms;publicHouse(int roomCount){rooms =newRoom[roomCount];for(int i =0; i < roomCount; i++){rooms[i]=newRoom(i +1);}}}
In composition, the container creates the parts in its own constructor.
And it does not expose them: there is no getRooms(). That code difference is the conceptual one.
Composition in code
In composition, the container creates the parts in its own constructor. And it does not expose them: there is no getRooms(). That code difference is the conceptual one.
Relaciones.javajava
// ASSOCIATION: they know each other, neither owns the otherpublicclassTeacher{privateCourse[] courses =newCourse[10];}// AGGREGATION: receives the parts from outsidepublicclassTeam{privatefinalPlayer[] players;publicTeam(Player[] players){this.players =Arrays.copyOf(players, players.length);}}// COMPOSITION: creates its parts and does not expose thempublicclassHouse{privatefinalRoom[] rooms;publicHouse(int roomCount){rooms =newRoom[roomCount];for(int i =0; i < roomCount; i++){rooms[i]=newRoom(i +1);}}}
Using an abstract class where an interface belongs burns the only available extends.
An interface with a default for every method stops being a contract and becomes an abstract class.
Every field of an interface is public static final: a global constant, not object state.
And if the part cannot live without the whole, it is composition: create it inside and do not expose it.
Common mistakes
Using an abstract class where an interface belongs burns the only available extends. An interface with a default for every method stops being a contract and becomes an abstract class. Every field of an interface is public static final: a global constant, not object state. And if the part cannot live without the whole, it is composition: create it inside and do not expose it.
Define Payable with pay, isAvailable and a default payIfPossible.
Implement it in CreditCard and DigitalWallet, which extends an abstract class with the email and an active flag.
In main, charge everyone the same amount in one loop, with no instanceof or casting.
Challenge: payment methods
Define Payable with pay, isAvailable and a default payIfPossible. Implement it in CreditCard and DigitalWallet, which extends an abstract class with the email and an active flag. In main, charge everyone the same amount in one loop, with no instanceof or casting.
DigitalPaymentMethod stores the email and the active flag, and leaves pay() abstract.
DigitalWallet.isAvailable() calls super.isAvailable() and adds its own condition.
The abstract class contributes the state
DigitalPaymentMethod stores the email and the active flag, and leaves pay() abstract. DigitalWallet.isAvailable() calls super.isAvailable() and adds its own condition.
DigitalWallet.javajava
publicabstractclassDigitalPaymentMethodimplementsPayable{protectedfinalString email;protectedboolean active =true;protectedDigitalPaymentMethod(String email){this.email = email;}@OverridepublicbooleanisAvailable(){return active;}// pay() stays abstract: each method charges its own way}publicclassDigitalWalletextendsDigitalPaymentMethod{privatedouble balance;@OverridepublicbooleanisAvailable(){returnsuper.isAvailable()&& balance >0;// reuses and refines}@Overridepublicbooleanpay(double amount){if(amount > balance)returnfalse;balance -= amount;returntrue;}}
CreditCard and DigitalWallet share no ancestor and live in the same Payable[].
The default decides for everyone: nobody asks what type each one is.
One loop, three methods
CreditCard and DigitalWallet share no ancestor and live in the same Payable[]. The default decides for everyone: nobody asks what type each one is.
MainCobros.javajava
Payable[] methods ={newCreditCard("4417",50000),newDigitalWallet("facu@mail.com",30000),newDigitalWallet("empty@mail.com",0)// no balance};for(Payable method : methods){method.payIfPossible(12500);}
An abstract class is an incomplete mold; an interface is a contract that does not use up your extends.
Start with the interface and add an abstract base only if there is shared state or logic.
And for any relationship, ask: if I destroy the whole, does the part still exist?
Key takeaways
An abstract class is an incomplete mold; an interface is a contract that does not use up your extends. Start with the interface and add an abstract base only if there is shared state or logic. And for any relationship, ask: if I destroy the whole, does the part still exist?