In addition to “abstraction” and “inheritance,” there are another two principles in OOP, “encapsulation” and “polymorphism.”
Encapsulation
You may have heard the phrase “information hiding,” which intends to conceal the detailed implementations of an object behind a higher level of abstraction. Information hiding is mainly for security concerns, while encapsulation is to keep data and class implementation details inside a class for complexity concerns. However, encapsulation combines internal data and methods and enables its internal data to be accessible from outside through its public methods. And the class has private instance variables that are only accessible by methods in the same class. This helps managing code that is to be updated frequently. This is known as: “encapsulate what varies,” which is one of the best practice design principles.
private int age; only accessible from inside class
public void setAge(int age); setter accessible from outside
public int getAge(); getter accessible from outside
There is a difference between abstraction and encapsulation. Abstraction is hiding complexity (i.e., implementation details) by using interfaces, while encapsulation is wrapping code (i.e., implementation) and data (i.e., value of variables) within the same class.
Polymorphism
With one interface, we can create multiple classes. Each class implements the same method with different details.
In the basic class design, we can create multiple constructors with different input parameters.
Similarly , we can use the same method name with a different set of input parameters in a class design. This is also called “overloaded methods.”
In a subclass, we can “override a method” defined originally in its superclass.
Problems
- 1.
Write an interface called GeometricObject, which declares two abstract methods: getPerimeter() and getArea().
- 2.
Write the implementation class Circle, with a protected variable radius, which implements the interface GeometricObject.