What are the four pillars of object-oriented programming in Java, and how does each one show up in real code?
There are four of them, and here is what each one looks like in real Java code.
Encapsulation means keeping the data of a class private and letting the class decide what may be done with it. The class exposes methods, and those methods keep the rules.
Abstraction means exposing what a thing can do while hiding how it does it. The caller works against a simple idea, such as a list of names, and does not care how the list is stored inside.
Inheritance means letting one class take the behaviour of another, so that a more specific class does not have to repeat what the general one already does.
Polymorphism means letting one call work on many different kinds of object, with the right behaviour chosen at run time.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Polymorphism: one list holding three kinds of animal.
List<Animal> animals = new ArrayList<Animal>();
animals.add(new Dog("Rex"));
animals.add(new Cat("Mia"));
animals.add(new Bird("Tweety"));
for (Animal animal : animals) {
// The right speak method is chosen at run time.
System.out.println(animal.getName() + " says " + animal.speak());
}
// Abstraction: the caller only knows the shape of the list.
animals.add(new Dog("Fido"));
System.out.println("the list holds " + animals.size() + " animals");
}
}
class Animal {
private final String name;
Animal(String name) {
this.name = name;
}
String getName() {
return this.name;
}
String speak() {
return "...";
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
@Override
String speak() {
return "woof";
}
}
class Cat extends Animal {
Cat(String name) {
super(name);
}
@Override
String speak() {
return "meow";
}
}
class Bird extends Animal {
Bird(String name) {
super(name);
}
@Override
String speak() {
return "tweet";
}
}
Each pillar is there to solve a particular problem. Encapsulation protects the data. Abstraction keeps the details from spreading. Inheritance removes duplication. Polymorphism lets you add a new kind of thing without changing the code that uses it.
The next question in this topic looks at the difference between the first two, because they are often mixed up.