OOP and design · Topic 3 of 12
Abstraction
Definition​
Abstraction means showing what something does and hiding how it does it. In Java you describe the "what" with an interface or an abstract class, and callers depend on that instead of on a concrete class.
Example code​
Checkout does not care how the payment is made
interface PaymentMethod {
String pay(int amount); // the "what": pay an amount
}
class Card implements PaymentMethod {
public String pay(int amount) { return "Charged " + amount + " to the card"; }
}
class Upi implements PaymentMethod {
public String pay(int amount) { return "Sent " + amount + " by UPI"; }
}
class Checkout {
String complete(PaymentMethod method, int amount) {
return method.pay(amount); // works with any payment method
}
}
class Demo {
public static void main(String[] args) {
Checkout checkout = new Checkout();
System.out.println(checkout.complete(new Card(), 500));
System.out.println(checkout.complete(new Upi(), 250));
}
}
// Output:
// Charged 500 to the card
// Sent 250 by UPI
Finished this page? Track your progress (saved only in your browser).