Introduction to Object-Oriented Programming in Java
Sani Yusuf
Lead Software Engineering Content Developer
// Car class
class Car {
// Battery capacity is only applicable
// to electric cars
public int batteryCapacity;
void drive() {
}
}
// Toyata class class Toyota extends Car { void drive(){ } }
// Man class public static class Main { public static void main(String[] args) { Toyota myToyota = new Toyota(); // All cars will inherit the "batteryCapacity" // even if they are not electric cars System.out.println( myToyota.batteryCapacity); // Not applicable } }
implements
keyword
// ElectricCar Interface
interface ElectricCar {
}
// Tesla implementing the
// ElectricCar interface
class Tesla implements ElectricCar {
}
UPPER_SNAKE_CASE
by conventionpublic static final
behind the scenes
interface ElectricCar {
// Implictly public static final
// Cannot be changed
int BATTERY_CAPACITY = 310;
}
abstract
by default without code implementationabstract
methods must be implemented in the subclassinterface ElectricCar { // Implictly public static final // Cannot be changed int BATTERY_CAPACITY = 310;
// This is an abstract method by default void charge();
// This is a concrete method void autoPark() { }
}
class Tesla implements ElectricCar { // Must be implemented public void charge() { } }
Introduction to Object-Oriented Programming in Java