Interfaces
Abstract classes
Inheritance
You don't know how it works
It has two operations - turnOn & turnOff
You can use it to turn on the lights, heater etc
Manipulate objects without
knowing how they work
Contract between the user of the code
and the one who wrote it
Useful when you have similar but not identical objects
public interface NAME {
void METHOD_NAME();
}public interface Vehicle {
int getPosition();
PaintColor getColor();
Driver getDriver();
int getTopSpeed();
void moveLeft();
void moveRight();
int getInitialSpeed();
VehicleType getVehicleType();
}Reuse all the methods and fields from other class
Create is a relationship
e.g. Car is a Vehicle
Add new fields and methods or replace existing ones
class SUBCLASS_NAME extends PARENT_NAME {
@Override
public void PARENT_METHOD_NAME() {
}
}Extend existing class
Replace parent
method
You can inherit only from 1 class
public class CLASS_NAME implements INTERFACE_NAME {
@Override
public void METHOD_NAME() {
}
// All methods from the interface
}A class can implement multiple interfaces
@Override tells the compiler to replace the parent method with the new one
public class BaseVehicle implements Vehicle {
@Override
public int getPosition() {
return position;
}
@Override
public PaintColor getColor() {
return color;
}
...
}public class BaseVehicle implements Vehicle {
protected int position;
...
}Protected components can be accessed only from the children of a class
public abstract class BaseVehicle implements Vehicle {
...
}BaseVehicle vehicle = new BaseVehicle();public class Car extends BaseVehicle {
...
}NO
YES
Abstract Classes Compared to Interfaces
Similarities:
Differences:
In the code:
public abstract class BaseVehicle implements Vehicle {
private PaintColor color;
private Driver driver;
private final int initialSpeed;
private int topSpeed;
protected int position;
public BaseVehicle(PaintColor color, Driver driver,
int initialSpeed, int topSpeed, int position) {
...
}
@Override
public int getPosition() {
return position;
}
...
}Constructor
implementation
More getters
Implement the missing methods
in Spaceship & Motorcycle