Abstraction in Java is the process of hiding internal implementation details and exposing only the essential functionality to the user.
Java provides two mechanisms to achieve abstraction:
Abstract Classes: Achieves partial abstraction (0% to 100%).
Interfaces: Achieves total abstraction (100%). (TO BE DISCUSSED)
Abstract Classes (Partial Abstraction)
An abstract class is a restricted class declared with the abstract keyword that cannot be instantiated directly.
It serves as a blueprint for subclasses and can contain a mix of both abstract methods (without bodies) and concrete methods (with bodies).
Key Rules
If a class contains at least one abstract method, the class itself must be declared abstract.
Subclasses must override all inherited abstract methods,otherwise its declared itself also abstract.
Code Example
Shopping Cart Example
public abstract class ShoppingCart
{
public abstract void buyNow();
public void details(){
System.out.println("Type your delivery address and Contact information");
}
public void payment(){
System.out.println("Pay using via credit card, UPI or select cash on delivery");
}
public void confirm(){
System.out.println("Place the Order");
}
}
public class AmazonShopping extends ShoppingCart {
public static void main(String[] args){
AmazonShopping buyProduct = new AmazonShopping();
buyProduct.buyNow();
buyProduct.details();
buyProduct.payment();
buyProduct.confirm();
}
public void buyNow(){
System.out.println("Open Amazon app and click the football jersey");
}
}

Top comments (0)