info@tutsfinder.in



Polymorphism

As the name suggest one name many forms, Polymorphism is the way of providing the different functionality by the functions having the same name based on the signatures of the methods.

For example: method calculate_area will definitely work for circle, square and triangle object.


Method overloading

In Method overloading, functions have same name but different no. of arguments, return type of the parameters.

• It can be implemented in both parent and child class.

• It is also known as compile time polymorphism.


Method Overriding

In method overriding, redefining inherit methods in subclasses. In this, declaration should be identical, code may be different. It is like having another version of the same product.

• It can be used to add more functionality to a method.

• It is also called as run time polymorphism.

• In overriding, a method has same name, same no. of arguments and same data type.



abstract class Vehicle{        //declare abstract class
    String model;

    public Vehicle(String model){        //abstract class with constructor
    System.out.println("Vehicle constructor called");
    this.model=model;
    }
}
class Car extends Vehicle{
public Car(String model){
    super(model);
    System.out.println("Bike constructor called");
    }
    public String toString(){
    return "Car model is "+super.model;
    }
}
public class Abstraction{
    public static void main(String[] args){
        Vehicle obj = new Car("BMW");
        System.out.println(obj);
        }
    }
}



Output:

Vehicle constructor called
Bike constructor called
Car model is BMW



Encapsulation

It is mechanism to encapsulate or wrap up all the data in a single entity it is known as encapsulation.

Encapsulation can be achieved in two ways:

1. By using setter and getter methods.

2. Making all variables as private.

For Example: Here ATM Machine is a class. It contains both data i.e. money and operations i.e. withdraw money, balance enquiry and they are integrated in a single entity called ATM. This is called Encapsulation.

class Car{
    private String carColor;
    private String carModel;

    public String getColor()
    {
        return carColor;
    }

    public String getModel()
    {
         return carModel;
    }

    public void setColor(String newColor)
    {
         carColor=newColor;
    }
    public void setModel(String newModel)
    {
        carModel=newModel;
    }
}

class Encapsulation{
    public static void main(String[] args)
    {
        Car obj = new Car();
        obj.setModel("BMW");
        obj.setColor("Black");

        System.out.println(obj.getColor()+" "+obj.getModel()+" looks awesome.");
    }
}


Output:

Black BMW looks awesome.