Abstraction is a feature of object-oriented programming in Java that allows you to create abstract classes and interfaces that define a set of methods that must be implemented by any class that implements them. Abstraction allows you to hide the implementation details of a class and focus on the functionality that it provides.
Here's an example of abstraction in Java:
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle");
}
}
class Rectangle extends Shape {
void draw() {
System.out.println("Drawing a rectangle");
}
}
public class TestShape {
public static void main(String args[]) {
Shape circle = new Circle();
Shape rectangle = new Rectangle();
circle.draw();
rectangle.draw();
}
}
In this example, we have an abstract Shape class that defines an abstract method called draw(). The Circle and Rectangle classes extend the Shape class and provide their own implementations of the draw() method. The TestShape class creates objects of the Circle and Rectangle classes and calls their draw() methods.
When you call the draw() method on the circle object, Java executes the implementation of the method in the Circle class, which prints "Drawing a circle" to the console. When you call the draw() method on the rectangle object, Java executes the implementation of the method in the Rectangle class, which prints "Drawing a rectangle" to the console.
Abstraction allows you to define a common set of methods that must be implemented by any class that extends an abstract class or implements an interface. This allows you to create more modular and reusable code, since you can define a set of methods that can be used by different classes without worrying about the specific implementation details of each class. It also allows you to create more specialized classes that provide their own unique behavior while still adhering to a common interface.