Introduction to Object-Oriented Programming in Java
Sani Yusuf
Lead Software Engineering Content Developer
// Abstract Car class
abstract class Car {
// Abstract drive method
abstract void drive();
// No Code Implementation
}
// Toyota class inherits Car class
class Toyota extends Car {
}
// Tesla class inherits Car class
class Tesla extends Car {
}
// Lamborghini class inherits Car class
class Lamborghini extends Car {
}
@Override
keyword allows you to create custom method implementations // Abstract Car class
abstract class Car {
// Abstract drive method
abstract void drive();
// No Code Implementation
}
class Toyota extends Car {
@Override // Keyword used to override
void drive() {
// Toyota specific implementation code
}
}
class Tesla extends Car {
@Override
void drive() {
// Tesla specific implementation code
}
}
class Lamborghini extends Car {
@Override
void drive() {
// Lamborghini specific implementation code
}
}
// ElectricCar interface
interface ElectricCar {
abstract void charge();
// No Code Implementation
}
@Override
is recommended when using interface methods
// Tesla class implementing
// ElectricCar interface
class Tesla implements ElectricCar {
// charge method must be implemented
@Override
void charge(){
// Tesla specific charge implementation
// Selective inheritance with interface
}
}
// Toyota class class Toyota { void drive() { // First implementation of drive method }
// Overloaded drive method void drive(int topSpeed) { // Second implementation of drive } }
// Honda class class Honda { // First Constructor public Toyota(String color, String model) { }
// Second Constructor public Toyota(String color, String model, String licensePlate) { } }
public class Main { public static void main( String[] args) { // First Constructor usage Honda hondaOne = new Honda("Red", "Accord");
// Second Constructor usage Honda hondaTwo = new Honda("Red", "Civic", "FST-1977"); } }
Introduction to Object-Oriented Programming in Java