Showing posts with label OOP concepts. Show all posts
Showing posts with label OOP concepts. Show all posts

07 August 2017

OOP - Encapsulation

Encapsulation binds properties and methods to a object defined by class.

Example:

Class Vehicle has private attributes and public getter and setter methods.

public class Vehicle {
    private String fuelType;
    private String capacity;

    public String getFuelType() {
        return fuelType;
    }

    public void setFuelType(String fuelType) {
        this.fuelType = fuelType;
    }

    public String getCapacity() {
        return capacity;
    }

    public void setCapacity(String capacity) {
        this.capacity = capacity;
    }
    
}

These attributes and methods bind to a object and object properties can be accessed via public methods.

"public","private","protected","default" are the access specifiers,which restrict the access of properties at various levels.Thus provides security to the object o the class while accessing.



OOP - Inheritance

Inheritance is about inheriting the properties and methods in sub classes to reuse them.

Define a class Engine

public class Engine {
    public static String getCapacity(){
        return "2.5";
    }
}

Define a class Vehicle which extends Engine class.

public class Vehicle extends Engine {
  public static void main(String args[]) {
    System.out.println("Vehicle capacity is "+ getCapacity()+" and fuel type is "+ getFuelType());
  }
  public static String getFuelType(){
        return "Diesel";
    }
}
We can observe main method uses methods in Engine class

output will be:

Vehicle capacity is 2.5 and fuel type is Diesel



OOP- Polymorphism Example

Example:

Define a Vehicle interface

public interface Vehicle {
    int getNumberOfTyres();

}

Define a Bus Class which implements Vehicle interface

public class Bus implements Vehicle {
    public int getNumberOfTyres() {
        return 6;
    }
}

Define a Car Class which implements Vehicle interface

public class Car implements Vehicle {
    public int getNumberOfTyres() {
        System.out.println();
        return 4;
    }
}

Define a Vehicle Service and execute the main program

public class VehicleService {

    public static void main(String args[]){
        Vehicle veh = new Bus();
        //Method on Bus class will be executed
        System.out.println("Number of Bus Tyres = "+veh.getNumberOfTyres());
        Vehicle veh = new Car();
       //Method on Car class will be executed
System.out.println("Number of Car Tyres = "+veh.getNumberOfTyres()); } }
Output will be like :
Number of Bus Tyres = 6
Number of Car Tyres = 4
which class method needs to be executed will be decided at run time and it is based on the created object.