Home Polymorphism in java

Polymorphism in java

Polymorphism means Single Interface in many forms.

CompileTimePolymorphism

which means Same name as different parameters.

 

Create a class CompileTimePolymorphism

CompileTimePolymorphism.java

public class CompileTimePolymorphism {

    public void a()
    {
        System.out.println("Method A");
    }

    public void a(int i)
    {
        System.out.println("Methods(int)");
    }

    public void a(String s)
    {
        System.out.println("Methods(String)");
    }

    public void a(int i,String s)
    {
        System.out.println("Methods(String,Int)");
    }
}

Main.java

public class Main {
    public static  void main(String[] args)
    {
        CompileTimePolymorphism ob = new CompileTimePolymorphism();
        ob.a();
        ob.a(20);
        ob.a("PHP");
        ob.a(20,"PHP");

    }

}

RunTimePolymorphism

Same name as same parameters

create a class Animal

Animal.java

public class Animal {

    //same name same parameter
    public void bark()
    {
        System.out.println("Bark");
    }

    public void run()
    {
        System.out.println("Run");
    }

}

Dog.java

public class Dog extends Animal{

    public void bark()
    {
        System.out.println("bbbb........");
    }

    public void run()
    {
        System.out.println("Run...................");
    }

}

Main.java

public class Main {
    public static  void main(String[] args)
    {
        //run time which method excution
        Animal obj = new Dog();
        obj.bark();
        obj.run();
    }

}

 

 

Comments are closed.