Sobes.tech
Junior — Middle

How can interaction between classes be represented using abstraction?

sobes.tech AI

Answer from AI

Interaction between classes when using abstraction in Java is usually built through interfaces or abstract classes. Abstraction allows hiding implementation details and providing only the necessary methods for interaction.

For example, one class can work with an object of another class through an interface, without knowing the specific implementation:

interface Vehicle {
    void move();
}

class Car implements Vehicle {
    public void move() {
        System.out.println("Car is moving");
    }
}

class Driver {
    void drive(Vehicle vehicle) {
        vehicle.move();
    }
}

public class Main {
    public static void main(String[] args) {
        Vehicle car = new Car();
        Driver driver = new Driver();
        driver.drive(car); // Interaction through abstraction
    }
}

Thus, the Driver class interacts with Vehicle through an abstract interface, without depending on the specific implementation of Car. This simplifies extensibility and code maintenance.