Java Abstraction
Abstraction in Java is a process of hiding the implementation details and showing only the essential features of the object. It helps in reducing programming complexity and effort by allowing the programmer to focus on what the object does instead of how it does it.
Ways to Achieve Abstraction
1. Abstract Classes
An abstract class is a class that cannot be instantiated and may contain abstract methods (methods without a body). It provides a base for subclasses to extend and implement the abstract methods.
Example:
public abstract class Shape {
// Abstract method
public abstract void draw();
// Regular method
public void display() {
System.out.println("Displaying shape");
}
}
public class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
public class Main {
public static void main(String[] args) {
Shape shape = new Circle();
shape.draw(); // Outputs: Drawing a circle
shape.display(); // Outputs: Displaying shape
}
}
2. Interfaces
An interface is a completely abstract class that contains only abstract methods (before Java 8). From Java 8 onwards, interfaces can have default and static methods with implementations.
Example:
public interface Animal {
void makeSound(); // Abstract method
}
public class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
animal.makeSound(); // Outputs: Bark
}
}
3. Abstract Classes vs. Interfaces
Abstract Class | Interface |
---|---|
Can have both abstract and concrete methods. | Before Java 8, can only have abstract methods. |
Can have instance variables. | Variables are public static final by default. |
Use extends keyword. |
Use implements keyword. |
A class can extend only one abstract class. | A class can implement multiple interfaces. |
4. Key Takeaways
- Abstraction focuses on exposing essential features while hiding the implementation details.
- Abstract classes provide a base for subclasses and can contain both abstract and concrete methods.
- Interfaces define a contract that implementing classes must fulfill.
- Use abstraction to reduce complexity and enhance code maintainability.
- Choose between abstract classes and interfaces based on the design requirements.