Wednesday, 24 October 2012

OOPS concept in Java

Object Oriented programming is about construction of inter related components which work together to complete the given task. These are called Java Objects.

In short OOPS concepts are mainly revolves around following 4 principle

Abstraction :- Abstraction is a way to segregate  implementation using Interface and Abstract in Java.
Way to use Abstract and Interface in Java is to extend and implement methods from the abstract class and interface.
Say for example if you create a Car as a abstract class and Engine as a Interface, where Car class containing  model method will vary for each car and it won't make sense to implement a generic model method in the Car class. In this case Java provides a abstract keyword to segregate the implementation to the child class and let child class provide its own  implementation as per its specification.
Similarly for Interface, any methods defined inside Interface is abstract by default, any class implementing the Interface should implement all methods defined in the Interface.Say Engine as a Interface which got fuel as one of its method, here every car will have a engine but its properties will vary for each car model, so by implementing Engine interface it is forced to provide its own properties for each method declared in Engine Interface.

Now what is the difference between Interface and Abstract and where to use them?

Main difference between Abstract and Interface is former can contain concrete methods whereas in Interface  all methods defined will by default be abstract(no concrete methods in Interface).
Use Interface if there are no generic concrete methods and you expect the class implementing this Interface should be forced to implement those methods. Abstract class, as it can contain concrete methods it is preferred super class on many scenarios, declaring class as abstract will also stop getting instantiated. Ideally use Abstract Class when you know something can be implemented on that class which can be used by the child class, but at the same time providing varying implementation for child class.

Encapsulation :- It is a way of hiding data in a class  by preventing outside class from changing the protected functionality. Encapsulation is achieved in Java by using private keyword.By making a method as private it is well hidden from outside the class including any child classes which extends this class. By this way the functionality of super class is not altered. Access to private methods can be achieved by setter and getter method which can be used by any classes to provide input and retrieve output from the private method.

Example of Encapsulation
class Employee{
    private int age;  //private variables examples of encapsulation
    private String name;
    private int salary;
    private Employee(int age, String name, String salary){
        this.age = age; = name;
        this.salary = salary;
    public void setSalary(int salary){
        this.salary = salary;
public int getSalary(){
return salary;

Inheritance :- Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. You could create a generic class with states and actions methods that are common to all sub-classes. The generic class is known as the parent (or superclass or base class) and the specific classes as children (or subclasses or derived classes). The concept of inheritance greatly enhances the ability to reuse code as well as making design a much simpler and cleaner process.

Example of Inheritance

Here is the sample code for a possible implementation of a Bicycle class as a super class
public class Bicycle {
    public int cadence;
    public int gear;
    public int speed;
    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    public void setCadence(int newValue) {
        cadence = newValue;
    public void setGear(int newValue) {
        gear = newValue;
    public void applyBrake(int decrement) {
        speed -= decrement;
    public void speedUp(int increment) {
        speed += increment;
A class declaration for a MountainBike class that is a subclass of Bicycle might look like this:
public class MountainBike extends Bicycle {
    // the MountainBike subclass adds one field
    public int seatHeight;
    // the MountainBike subclass has one constructor
    public MountainBike(int startHeight,
                        int startCadence,
                        int startSpeed,
                        int startGear) {
        super(startCadence, startSpeed, startGear);
        seatHeight = startHeight;
    // the MountainBike subclass adds one method
    public void setHeight(int newValue) {
        seatHeight = newValue;
MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a method to set it. Except for the constructor, it is as if you had written a newMountainBike class entirely from scratch, with four fields and five methods. However, you didn't have to do all the work. This would be especially valuable if the methods in the Bicycle class were complex and had taken substantial time to debug.

Polymorphism :- Polymorphism is the ability of an object to take on many forms. In programming languages polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. The three types of polymorphism are: ad-hoc (overloading and overriding), parametric (generics) and dynamic method binding.

Overloaded methods are methods with the same name signature but either a different number of parameters or different types in the parameter list. For example draw methods may behave differently for different input, say you input two integer nos to draw a rectangle, one integer no to draw a square. By defining a method for handling each type of parameter you control the desired effect.
draw(int size) -- draws square
draw(int len, int width) -- draws rectangle

Overridden methods are methods that are redefined within an inherited or subclass. They have the same signature and the subclass definition is used.
by Overriding paint() method in subclass, functionality of paint method is customized to subclass.

Parametrics are generic typing procedures.

Dynamic (or late) method binding is the ability of a program to resolve references to subclass methods at runtime. For example assume that three subclasses (Cat and Dog) have been created based on the Animal abstract class, each having their own speak() method. Although each method reference is to an Animal (but no animal objects exist), the program is will resolve the correct method reference at runtime.