Abstraction is one of the four fundamental principles of object-oriented programming (OOP), along with encapsulation, inheritance, and polymorphism. Abstraction is the concept of hiding the complex implementation details and showing only the essential features of an object. It allows a programmer to focus on what an object does rather than how it does it.
In Java, abstraction can be achieved through abstract classes and interfaces.
Example of Abstraction using Abstract Classes
abstract class Shape {
// Abstract method
abstract void draw();
// Concrete method
public void display() {
System.out.println("Displaying shape.");
}
}
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 TestAbstraction {
public static void main(String[] args) {
Shape circle = new Circle();
Shape rectangle = new Rectangle();
circle.draw(); // Calls the draw method in Circle
rectangle.draw(); // Calls the draw method in Rectangle
circle.display(); // Calls the concrete method in Shape
}
}
Drawing a circle.
Drawing a rectangle.
Displaying shape.
Explanation: An abstract class, such as Shape
, can contain both abstract methods (methods without a body) and concrete methods (methods with a body). Subclasses like Circle
and Rectangle
must implement the abstract methods. This allows for a common interface (draw
method) while enabling specific implementations in each subclass.
xxxxxxxxxx
interface Drawable {
void draw(); // Abstract method
}
class Circle implements Drawable {
public void draw() {
System.out.println("Drawing a circle.");
}
}
class Rectangle implements Drawable {
public void draw() {
System.out.println("Drawing a rectangle.");
}
}
public class TestInterfaceAbstraction {
public static void main(String[] args) {
Drawable circle = new Circle();
Drawable rectangle = new Rectangle();
circle.draw(); // Calls the draw method in Circle
rectangle.draw(); // Calls the draw method in Rectangle
}
}
Drawing a circle.
Drawing a rectangle.
Explanation: An interface, such as Drawable
, contains abstract methods that must be implemented by any class that claims to implement the interface. This provides a way to ensure that different classes adhere to a common set of behaviors.