Abstraction in Java is a core Object-Oriented Programming (OOP) principle that focuses on hiding internal implementation details and showing only the essential functionality to the user.
Why We Use Abstraction:
Reduces Complexity: By hiding unnecessary technical details, abstraction makes large systems easier to understand, manage, and navigate.
Enhances Security: It protects sensitive internal logic and data by only allowing users to access what is necessary through a public interface.
Improves Maintainability: Changes to the internal code (the "how") do not break the rest of the application as long as the public abstract structure remains the same.
Promotes Code Re-usability: It allows you to define common behaviors in one place (an abstract class) and share them across multiple sub classes.
In Java, we use abstraction when we want to hide the complex implementation details of a system and only show the essential features to the user.
To Improve Maintainability: Since the internal implementation is hidden, you can change the underlying code without affecting the code that uses the abstraction.
How to create: Use the abstract keyword for the class and its unimplemented methods.
How to use: Inherit the abstract class using the extends keyword in a subclass, which must then provide implementations for the abstract methods.
Key Rules for Abstraction:-
No Instantiation: You cannot create an object of an abstract class or an interface.
Method Signature: If a class has at least one abstract method, the class itself must be declared abstract.
Implementation Requirement: Any concrete (non-abstract) subclass extending an abstract class or implementing an interface must override and implement all inherited abstract methods.
Constructors: Abstract classes can have constructors (to initialize shared fields), but interfaces cannot
Top comments (0)