Is Java pure OO? Not exactly, since primitives are not implemented as objects. Smalltalk for example, is purely OO.
-
Abstraction:
- Extract all the common attributes and behaviour for a given set of classes and move them one level up and that will be your first level of abstraction.
- And so on.
-
Polymorphism:
Means different shapes. Yes, we have all heard that one before. We’ve also seen the example of Circle, Triangle and Square inheriting from Shape and overriding the draw() method often enough. However it all became quite clear to me only when I saw it like this:
A Triangle inherits from Shape and implements Drawable.
Triangle figure = new Triangle();
Object obj = figure;
Shape shape = figure;
Drawable drawable = figure;
Now notice that the same darned object, figure, can behave as a Shape, a Triangle, an Object or even a Drawable, all depending on the type of the reference variable. Impressive, huh?
(Also see: runtime and compile time polymorphism)
-
Inheritance:
- This one is quite simple. An IS-A relationship.
- Inherit non-private attributes and methods of a super class
-
Encapsulation:
- Grouping together of common functionality.
- Hiding of internal algorithms. Car.moveForward() will move the car forward. How the car implements moving forward is nobody else’s darned business.
- Only revealing the interfaces required to interact with it.
- Data protection, usually through getters and setters that will prevent data corruption.
- Prudent encapsulation = robust design = easy refactoring.
-
Composition:
- HAS-A relationship. Objects built or composed from other objects. Simple concept but with profound design implications.