Junior
Where and for what is the abstract modifier used?
sobes.tech AI
Answer from AI
The abstract modifier is used for:
-
Classes:
- Declares a class as abstract.
- An abstract class cannot be instantiated directly (
new AbstractClass()). - It can contain both abstract and concrete (with implementation) methods.
- The goal is to provide a template (partial or complete) for subclasses and define common properties/behaviors.
- A subclass of an abstract class must either implement all its abstract methods or be declared as abstract itself.
// Example of an abstract class abstract class Shape { private String color; public Shape(String color) { this.color = color; } // Abstract method - without implementation public abstract double getArea(); // Concrete method public String getColor() { return color; } } -
Methods:
- Declares a method as abstract in an abstract class.
- An abstract method has no body (implementation), ending with a semicolon.
- It requires non-abstract subclasses to provide a concrete implementation of this method (override it).
- Used to define behavior that should be specific to each subclass, but the general template is set in the superclass.
// Example of usage in an abstract class Shape abstract class Shape { // ... public abstract double getArea(); // Abstract method } // Subclass implementing the abstract method class Circle extends Shape { private double radius; public Circle(String color, double radius) { super(color); this.radius = radius; } @Override public double getArea() { return Math.PI * radius * radius; // Implementation of the abstract method } }
Main purposes of use: polymorphism, defining a common interface for a class hierarchy, enforcing subclasses to implement certain methods.