Abstraction in Java is a fundamental concept in OOP, and it allows developers to create classes and objects that focus on essential functionality and hide unnecessary details. By using abstraction, Java programs become easier to maintain, understand, and scale.
Table of Contents
Abstract Classes in Java
Abstract classes in Java are classes that cannot be instantiated directly and must be subclassed. These classes provide a way to define common behavior and properties for related classes without defining implementation details.
Implementing Abstract Classes in Java
public class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(String color, double length, double width) {
super(color);
this.length = length;
this.width = width;
}
public double getArea() {
return length * width;
}
public double getPerimeter() {
return 2 * (length + width);
}
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle("blue", 5, 10);
System.out.println("Color: " + rectangle.getColor());
System.out.println("Length: " + rectangle.getLength());
System.out.println("Width: " + rectangle.getWidth());
System.out.println("Area: " + rectangle.getArea());
System.out.println("Perimeter: " + rectangle.getPerimeter());
}
}
Output

Interfaces in Java
Interfaces in Java are similar to abstract classes, but they define a set of methods without any implementation details. Interfaces provide a way to define contracts that classes must implement to achieve a particular behavior or functionality.
Implementing Interfaces in Java
public class Dog implements Animal {
public void speak() {
System.out.println("Bark");
}
public void eat() {
System.out.println("Dog food");
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.speak();
myDog.eat();
}
}
}
Output

Differences Between Abstract Classes and Interfaces
Here are some key differences between the two:
- Abstract classes can have abstract and non-abstract methods, while interfaces can only have abstract methods.
- An abstract class can provide default implementations for some or all of its methods, while interfaces cannot provide any implementation details.
- A class can implement multiple interfaces, but it can only extend one abstract class.
- An abstract class can have instance variables, while interfaces can only have constant variables.
Conclusion
Abstraction in Java is an essential programming concept that enables the creation of modular, reusable, and extensible code. It can be implemented through abstract classes and interfaces, which respectively provide common behavior and define a contract for implementing classes. This approach leads to more maintainable and flexible code.