Can you write one small program that demonstrates all four pillars of object-oriented programming at the same time?
Yes. Here is one small program that shows all four of them at once, and then we can point at which line is which.
public class Main {
public static void main(String[] args) {
Storage store = new MemoryStorage();
DailyReport report = new DailyReport(store);
report.add(new Entry("alpha", 10));
report.add(new Entry("beta", 20));
System.out.println(report.summary());
}
}
So here is where each pillar shows up.
the pillar where it is in the program
---------------- -----------------------------------------------
encapsulation the fields of DailyReport are private and the
methods check what goes in
abstraction DailyReport talks to a Storage, and it does not
know what Storage really is
inheritance MemoryStorage extends the Storage class
polymorphism the program holds a Storage and it does not know
which one it has
And the last two are worth explaining because they are often confused. Inheritance is the extends in the line class MemoryStorage extends Storage. Polymorphism is the fact that the line Storage store = new MemoryStorage() works, and that the report does the same thing whatever kind of storage it was given. So one line of the program is inheritance and another line is polymorphism, and they are different ideas.
And there is one detail worth knowing about. Encapsulation and abstraction are both about hiding things, but they hide different things. Encapsulation is about the internal state of one class and it is about keeping that state valid. Abstraction is about the way that one class talks to another, and it is about making the caller not need to know the details.
So the rule to remember is this. One program can show all four, and the pillars are about hiding state, simplifying an interface, reusing a parent, and swapping an implementation.
The next two questions in this topic name the four pillars and explain the difference between the two hiding ones.