❌

Reading view

There are new articles available, click to refresh the page.

Polymorphism

what is Polymorphism?

  • It is a feature of object oriented programming(oops)
  • polymorphism means "many forms". It allow a method(method overloading & overriding) or object(static & dynamic binding) to behave in multiple ways,depending on the context or usage or situation.

Types Of Polymorphism:-

1.Compile-Time Polymorphism (static Binding/method overloading)

  • when a class has two or more same method name , different parameter list is called compile-time Polymorphism.Binding type Static binding.

Example:-

package polymorphism;


//Method Overloading: Different Number of Arguments 
public class Calculator {


    public int addTwoElements(int a , int b)
    {
        return a+b;

    }

    public int addThreeElemets(int a , int b ,int c)

    {
        return a+b+c;

    }

    // Method Overloading: Different Type of Arguments
    public static int  multiply(int a ,int b)

    {

        return a*b;
    }

    public static double division(double a ,double b)

    {

        return a/b;

    }
    // can not  overloaded if you different return type 
    //int add(int a, int b) { return a + b; }
    //double add(int a, int b) { return a + b; } 


    /*
     * can’t overload by changing between static and non-static?
     * 
     * static void display(int a) {}
    void display(int a) {}  //
     * 
     * 
     */
    public static void main(String args[])
    {
        Calculator  cal = new Calculator();

        System.out.println(cal.addThreeElemets(1, 2, 3));
        System.out.println(cal.addTwoElements(10, 20));
        System.out.println(multiply(10,5));   
        System.out.println(division(10,5));


    }

}




2.Run-Time Polymorphism(Dynamic Binding / Method overriding)

  • Same method name and signature ,different class (child class overrides parent ) is called method overriding
  • Decided at runtime,Binding type: Dynamic binding.
  • Method overriding is for achieving run-time polymorphism.

Rules of Method overriding:-

  1. same arguments - the method in child class must have same parameter as in the parent class. 2.same or compatible return type
  • return type must be the same or subclass of the parent method return type(subclass method must match the parent class method's name, parameters, and return type. ).

3.Access level not more restrictive:-
The child method can not have lower access level than the parent.

example:-

  • if parent method is public ,child method can not be private or protected.

4.Must be inherited
only the methods that are inherited by the child class can be overridden.

  1. final & private methods can not be overridden
  2. static method can not be overridden ,you can re-declared but not overridden.

7.same package -more freedom

if the child class is in same package ,it can override all methods except private or final ones.

8.Different package -less freedom

If the child is different package , it can only override public or protected methods(not default/package-private)

9.Constructors can not be overridden
constructor can not inherited ,so they can not be overridden.(constructor is implicitly final)

10.Exception -overriding rule [TBD]

  • The child method can throw unchecked exceptions freely.
  • It can throw fewer or narrower checked exceptions, but not broader ones.

How to used:-

parent class reference can be used to refer to a child class object , this helps to you code flexible and reusable code.


About reference variable:-

  • Every object is accessed through a reference variable. it is a fixed type ,once you created you can not to be changed , it can refer own type or subclass object ,it can be class type or interface type. this type reference to decide what method can be accessed.

Example:-

package polymorphism;

public class Animal {

    void sound()
    {
        System.out.println("Animal makes a sound");
    }


    void type()
    {
        System.out.println("This is a general animal");
    }
}



package polymorphism;

public class Dog extends  Animal {


    void sound()
    {
                super.sound();// Method Overriding: Using the super Keyword
        System.out.println("Dog barks");
    }
    void guard()
    {
        System.out.println("Dog gurads the house");
    }

    public static void main(String[] args) {

        Animal a;

        a = new Dog();
        a.sound();
        a.type();
    //  a.guard(); not allowed only override method only allowed 
        Dog c = (Dog) a;
        c.guard();
    }

}

package polymorphism;

public class Cat extends Animal {

    void sound()
    {
        System.out.println("cat meow");
    }
    void work()
    {
        System.out.println(" catching the mouse and  sleep a  lot");

    }
    public static void main(String[] args) {

        Animal a;

        a = new Cat();
        a.sound();
        a.type();
        //a.work(); only allowed Animal override in cat class
}


}

Dynamic Binding (Run time Polymorphism)

  • Dynamic binding means method call is resolved at runtime based on the object type ,not reference type.
//superclass 

public class Water_Animals {

    public void move()
    {
        System.out.println("water animal swim in sea");
    }
    public void foodType()
    {
        System.out.println("water animal eithter veg or non_veg");
    }

}

// sub class  

package polymorphism;

public class Shark  extends Water_Animals {

    @Override
    public void move()
    {
        System.out.println("i move faster to and hungry hunter of sea");

    }

    @Override
    public void foodType()
    {
        System.out.println("i eat Non-Veg all time");
    }
    public static void main(String args[]) {


        Water_Animals wa = new Water_Animals(); // normal object (only  access method/variables  Water_Animals)
        Shark  shark = new Shark(); // normal object ,Can access both Shark and inherited Water_Animals non-static members
        Water_Animals waterAnimal = new Shark (); //upcasting(Child object, Parent reference), You can access only methods/variables declared in Water_Animals, Cannot access Shark-specific methods/fields unless overridden
         Shark  sh = (Shark) waterAnimal;
         //Downcasting (Parent reference cast back to Child),You can now access both Water_Animals and Shark members

// (water_Animal  reference )water_Animal wateranimal = new Shark()  // Shark object

    }


}

When: Happen at runtime
used IN: Method overriding
Resolves: Based on actual object(not reference type)
Other Names : Run-time polymorphism/late binding.

Static Binding:-

  • Static Binding also called compile time or Early Binding it means call is decide by the compiler at compile time ,not a runtime. Based on Reference type and method signature. used in method overloading. method types happen static,final , private , non-static or overloaded methods ( same class happen).
  • performance faster than dynamic binding.
❌