Easy java core-java

What are the four principles of object-oriented programming in Java?

The 30 second answer

Encapsulation, inheritance, polymorphism and abstraction. Encapsulation hides an object's state behind methods, so I keep fields private and validate in setters or constructors. Inheritance lets a class reuse and extend another with extends. Polymorphism means one reference type, many behaviours: a PaymentMethod variable can hold a Card or a Wallet, and the right pay method runs at runtime. Abstraction means exposing what an object does, through interfaces and abstract classes, and hiding how.

<!-- level: 1 --> <!-- must_know: true -->

public interface PaymentMethod {          // abstraction: what, not how
    void pay(long cents);
}

public class Card implements PaymentMethod {
    private final String token;           // encapsulation: private state
    public Card(String token) { this.token = token; }
    @Override public void pay(long cents) { System.out.println("card " + cents); }
}

public class Wallet implements PaymentMethod {
    @Override public void pay(long cents) { System.out.println("wallet " + cents); }
}

PaymentMethod method = new Wallet();      // polymorphism: decided at runtime
method.pay(500);                          // prints "wallet 500"
  • Encapsulation: bundle data with the methods that work on it and hide the data (private fields, public behaviour). The object protects its own invariants.
  • Inheritance: a subclass extends a superclass and inherits its members. Java allows one superclass but many interfaces. Prefer composition when the relationship is not a true "is-a".
  • Polymorphism: an overridden method is chosen by the object's runtime class, not the variable's declared type (dynamic dispatch). Overloading is the compile-time kind.
  • Abstraction: model only what matters to the caller. Interfaces and abstract classes define the contract.

A strong follow-up example is replacing a giant if-else on payment type with polymorphism: see New payment method added; PaymentService is a giant if-else on type?.

Sources (1)
  1. dev.java: Object-oriented programming conceptsdev.java