Abstraction is the concept of hiding the comples implementation details and showing only the essential features of the object. It is achieved using abstract classes and interfaces.
1. Abstract Class:
By defining abstract class we can create abstract methods and concrete methods that have a method body. For create abstract class must have abstract keyword
Suppose we create an abstract class and the abstract class has an abstract method. Then if any class inherits this abstract that subclass should overwrite the abstract method. otherwise you will get error.
Example:
abstract class Vehicle {
// Abstract method (no method body implementation)
abstract void startEngine();
// Concrete method (with method body implementation)
void stopEngine() {
System.out.println("Engine stopped");
}
}
class Car extends Vehicle {
// implementing the abstract method
void startEngine() {
System.out.println("Car engine started");
}
}
public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car();
myCar.startEngine(); // Output: Car engine started
}
}
2. Interface:
Interface is a complete abstract class. In interface we can declare method with empty bodies. like abstract method. interface methods are abstract methods.
In inheritance, Class should extends and Interface should implements.
Example:
interface Vehicle {
void startEngine();
}
class Car implements Vehicle {
// implementing the interface method startEngine
public void startEngine() {
System.out.println("Car engine started");
}
}
public class Main {
public static void main(String[] args) {
Vehicle myCar = new Car();
myCar.startEngine(); // Output: Car engine started
}
}
Interface cannot have constructor.
A class can implements multiple interfaces