Core Module
12 min forge
Java Abstraction
Abstract classes, partial implementation, and implementation hiding.
Java Abstraction
π What is it
Abstraction is the process of hiding the implementation details and showing only the functionality to the user. In Java, abstraction is achieved using Abstract Classes and Interfaces.
β‘ When to use
Use abstract classes when you have a base class that should not be instantiated on its own, but provides a common template for its subclasses (e.g., Shape as a base for Circle and Square).
ποΈ Key Concepts
- Abstract Class: A class declared with the
abstractkeyword. It can have both abstract (no body) and non-abstract methods. - Abstract Method: A method that is declared without an implementation.
- Partial Abstraction: Abstract classes can provide partial implementation (unlike interfaces which were fully abstract before Java 8).
π» Code example
java Standardabstract class Shape { String name; Shape(String name) { this.name = name; } // Abstract method (must be implemented by subclasses) abstract double area(); void displayName() { System.out.println("This is a " + name); } } class Circle extends Shape { double radius; Circle(double radius) { super("Circle"); this.radius = radius; } @Override double area() { return Math.PI * radius * radius; } }
β Common mistakes
- Instantiating: Trying to do
new Shape()(abstract classes cannot be instantiated). - Missing implementation: Forgetting to implement an abstract method in a non-abstract subclass.
- Final Abstract: Declaring an abstract class as
final(it's a contradiction; final classes cannot be extended).