In Java, abstraction is the process of hiding the implementation details of a class or method and exposing only the necessary information to the user.
Abstraction is achieved in Java using abstract classes and interfaces.
An abstract class is a class that cannot be instantiated and is used to provide a common interface or implementation for its subclasses. An abstract class can contain both abstract and non-abstract methods. Abstract methods are methods that do not have an implementation, and they must be overridden by a subclass. Non-abstract methods are methods that have an implementation and can be used by a subclass.
An interface is a collection of abstract methods that define the behavior of a class. A class can implement one or more interfaces, and it must provide an implementation for all the abstract methods of the interfaces it implements.
Here is an example of an abstract class and an interface in Java:
public abstract class Shape { private String color; public Shape(String color) { this.color = color; } public String getColor() { return color; } public abstract double getArea(); } public interface Resizable { public void resize(double factor); }
In this example, the Shape
class is an abstract class that contains an abstract method called getArea
. The getArea
method does not have an implementation, and it must be overridden by a subclass.
The Resizable
interface is an interface that contains an abstract method called resize
. The resize
method does not have an implementation, and it must be implemented by a class that implements the Resizable
interface.
Abstraction is useful when you want to provide a common interface or implementation for a group of related classes, and it allows you to design flexible and modular systems by decoupling the implementation details from the interface.