Skip the definitions. Show me encapsulation, abstraction, inheritance and polymorphism, each in about ten lines of code, and then tell me when inheritance is the wrong tool.
OOP examples beat definitions: a class refusing a bad withdrawal shows encapsulation, a caller depending on an interface shows abstraction, a subclass reusing a parent method shows inheritance, and one loop running different overrides shows polymorphism. Inheritance is wrong when the child breaks a parent promise.
Answer
Short answer
OOP examples prove understanding faster than definitions. Encapsulation is a class that refuses to enter an invalid state. Abstraction is a caller that depends on an interface and not on the class behind it. Inheritance is a subclass reusing its parent's code, and polymorphism is one call running different code depending on the object. Inheritance is the wrong tool when the child cannot honour everything the parent promises.
Was this answer helpful?
Likely follow-ups
- Your BankAccount has no setBalance method. How would a test put an account into a known starting state?
- Change Shape from an interface to an abstract class. What can you now put in it, and what have you given up?
- Which method runs if Circle overloads area(double scale) and you call shape.area() through a Shape reference?
- Rewrite the Employee hierarchy so contractors and salaried staff share payslip logic without a common superclass.
Related questions
- Where does encapsulation or polymorphism change a design, and how do you decide between composition and inheritance?mediumAlso on polymorphism and composition6 min
- What are the four pillars of OOP, and what is the difference between abstraction and encapsulation?easyAlso on polymorphism5 min
- Implement a thread-safe pool of N connections with acquire, release and a timeout.hardAlso on java6 min
- Give me a subclass that the compiler accepts but that still breaks the Liskov substitution principle. What rule does it break?mediumAlso on polymorphism5 min