Encapsulation

Principle of OOP

What is encapsulation?

Why it is important?

Code improvement using encapsulation

Encapsulation in Design Patern

Contents:

Inheritance

Principle of OOP

Polymorphism

Encapsulation

Abstraction

Recap

What is Inheritance ?

Without Inheritance

With Inheritance

Child class can reuse attribute and method in parent class

What is Polymorphism ?

 Many Forms. The ability to take different form.

 

An animal at the same time can have different characteristic.

 

Like a cow at the same time is a sport animal, a milk animal, and is also a meat animal.

 

So the same animal posses different behavior in different situations. This is called polymorphism.

What is Encapsulation ?

 

  • Reducing dependencies between objects by hiding the internal representation of an object behind specific method.
  • Concept of bundling data related variables and properties with behavioral methods in one class or code unit.

Example of starting a car

 

The Process Flow

What User Do

Why it is important ?

  • Allow use of an item through a set of simple actions. You don't need to know the internals.
  • In term of code, you use item through an object method rather than through direct object attributes.
  • An approach for restricting direct access to some of the data structure elements (fields, properties, methods).

Example

public class Car {

 private String model;
 private int year;
 private double price;
 
 Car(String model,int year,double price){
  setModel(model);
  setYear(year);
  setPrice(price);
 }
 
 //setter
 public void setModel(String model) {
  this.model = model;
 }
 public void setYear(int year) {
  this.year = year;
 }
 public void setPrice(double price) {
  this.price = price;
 }
 
 //getter
 public String getModel() {
  return model;
 }
 public int getYear() {
  return year;
 }
 public double getPrice() {
  return price;
 }
}
public class Main {

 public static void main(String[] args) {
   
  Car car1 = new Car("Mustang",2021,9999.99);
  
  car1.setModel("Corvette");
  car1.setYear(2022);
  car1.setPrice(5000);
  
  System.out.println(car1.getModel());
  System.out.println(car1.getYear());
  System.out.println(car1.getPrice());
 }

}

Car Class

Main Class

Code Before and After

let baseSalary = 4000;
let overtime = 10;
let rate = 20;

function getWage(baseSalary, overtime, rate){
 return baseSalary + (overtime * rate)
}
let employee = {
    baseSalary: 4000,
    overtime: 10,
    rate: 20,
    getWage: function() {
    	return this.baseSalary + (this.overtime * this.rate)
    }
};

employee.getWage();

Before

After

"The best function are those with no parameters!"

 

Uncle Bob - Robert C Martin

Example of design patern that use encapsulation

Stratergy Patern

Encapsulation

By Syafiq bin abdul rahman