OOP: Abstraction in Java

Abstract class

public abstract class Vehicle{
public String name;

public abstract void move();
public abstract void stop();
}
public class Car extends Vehicle {

@Override
public void move() {
System.out.println("Car is driving");
}

@Override
public void stop() {
System.out.println("Car is stopped");
}
}

Overriding rules:

1. the method name should be same.

2. the number, order, and data type of argument should be same. Data type can be covariant as well.

3. access modifier should be same or more accessible.

4. if overriding method throws exception in the method declaration. Exception should be same or smaller(child exceptions) than parent’s class method or no exception at all.

public class Motorcycle extends Vehicle {

@Override
public void move() {
System.out.println("Motorcycle is driving");
}

@Override
public void stop() {
System.out.println("Motorcycle is stopped");
}
}
public class Main {
public static void main(String[] args) {
// we cannot assign abstract class directly
// Vehicle vehicle = new Vehicle();

Vehicle vehicle = new Car();
vehicle.drive();
// a lot of code here ...

vehicle.stop();
}
}
public class Main {
public static void main(String[] args) {
Vehicle vehicle = new Motorcycle();
vehicle.drive();
// a lot of code here ...

vehicle.stop();
}
}

Interface

public interface Vehicle {
public static final String str;
// private String str1; does not compile
void drive(); // public abstract will be injected by default
void stop(); // public abstract will be injected by default
// static method can have a body
public static String setStr(String strInput) {
str = strInput;
}
// default method can have a body
public default void printStr() {
System.out.println(str);
}
}
public class Car implements Vehicle {

@Override
public void move() {
System.out.println("Car is driving");
}

@Override
public void stop() {
System.out.println("Car is stopped");
}
}
public class Motorcycle implements Vehicle {

@Override
public void move() {
System.out.println("Motorcycle is driving");
}

@Override
public void stop() {
System.out.println("Motorcycle is stopped");
}
}
public class Main {
public static void main(String[] args) {
// we cannot assign interface directly
// Vehicle vehicle = new Vehicle();

Vehicle vehicle = new Car();
vehicle.drive();
// a lot of code here ...

vehicle.stop();
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store