www.000webhost.com
/** * Created by PhpStorm. * User: Rahul * Date: 12/10/2015 * Time: 2:54 AM */ OOP Concept : Polymorphism


OOP concept : Inheritance

Core Java

Polymorphism


The word "polymorphism" means "many forms". It comes from Greek word
"poly" (means -> many) and "morphos" (means -> form).

For Example -

A BOY start in LOVE with the word FRIENDSHIP, but the GIRL ends LOVE with the world FRIENDSHIP.
word is same but attitude is diffrent, This beautiful concept is nothing but polymorphism. :-)


Polymorphism in Java has two types:

Method overloading is an example of static polymorphism, while method overriding is an example of dynamic polymorphism.
An important example of polymorphism is how a parent class refers to a child class object. In fact, any object that satisfies more than one IS-A relationship is polymorphic in nature.
For instance, let’s consider a class Animal and let Cat be a subclass of Animal. So, any cat IS animal. Here, Cat satisfies the IS-A relationship for its own type as well as its super class Animal.


Overloading in Java

In same class, if name of the method remains common but the number and type of parameters are different, then it is called method overloading in Java.

in C-language two method heaving the same name but diffrent types of arument is not allowed


methods overloading



Method overloading example

		class functionOverload {
		    /*
		     * void add(int a, int b) // 1 - A method with two parameters {
		     * int sum = a + b; System.out.println(\"Sum of a+b is \"+sum);
		     * }
		     */

		    void add(int a, int b, int c)
		   {
				int sum = a + b + c;
				System.out.println(\"Sum of a+b+c is \"+sum);
			}
		    void add(double a, double b)
		    {
				double sum = a + b;
				System.out.println(\"Sum of a+b is \"+sum);
			}

		    void add(String s1, String s2)
		    {
		       String s = s1 + s2;
		       System.out.println(s);
		    }
		}
____________________________________________________________________

		class overLoading
		{
			 public static void main(String[] args)
				{
					functionOverload obj = new functionOverload();
					obj.add(1,2);
					obj.add(\"Life at \", \"?\");
					obj.add(11.5, 22.5);
				}
		}


Constructor Overloading



Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.
The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.

Constructor overloading example

	class Room
	{
	    double length, breadth, height;
	    Room(double l, double b, double h)
	    {
	        length = l;
	        breadth = b;
	        height = h;
	    }

	    Room()  {
	        length = -1;
	        breadth = -1;
	        height = -1;
	    }

	    Room(double len)  {
	        length = breadth = height = len;
	    }

	    double volume() 	    {
	    	        return length * breadth * height;
	    }
	}
 _______________________________________________

	class OverloadConstructors
	{
	    public static void main(String args[])
	    {
	        Room a = new Room(20, 30, 40);
	        Room b = new Room();
	        Room c = new Room(10);
	        double vol;
	        vol = a.volume();

	        System.out.println("Volume of room a is " + vol);
	        vol = b.volume();
	        System.out.println("Volume of room b is " + vol);
	        vol = c.volume();
	        System.out.println("Volume of room c is " + vol);
	    }
	}

in overloading method resolution is always takes care by compiler based on reference type - hence overloading is consider as compile time polymorphism, static polymorphism, early binding


Special cases in OverLoading


1. Automatic promotion :

When resolving overloaded methods if exact method is not available the we do not get any compile time error immediately, the compiler first promotes the arguments to the next level and checks whether the matched method is available, if its available then compiler considers it, otherwise promotes it to next level. This process will continue untill all possible promotions are completed. If no match is found we would get compiler error!
To illustrate this lets consider the belove example


		class Sample {
			public static void m1(int i) {
			    System.out.println("Int arg");
			}
			public static void m1(float f) {
			    System.out.println("Float arg");
			}
				 public static void main(String [] args)
				 {
					Sample s1 = new Sample();
					s1.m1(10); 		// Int-arg
					s1.m1(10L); 		//Float arg
					s1.m1(10.5f); 	//Float arg
					s1.m1(10.5); 		// compiler error "Cannot find symbol"
				}
		}

Description -
In the above example you can notice a long is automatically promoted to Float and hence we get output as “Float arg” , but a double cannot be downgraded to float hence compiler error.



2. In overloading, child class will get more priority than object class.

Lets take a couple of examples to illustrate this point more clearly


class Test
{
	public void m1(Object o)
	{
		System.out.println("Object here");
	}

	public void m1(String s)
	{
		System.out.println("String here");
	}

	public static void main(String[] args)
	{
		Test t = new Test();
		t.m1("Harsha"); //String here
		t.m1(new Object()); //Object here
		t.m1(null); //String here
	}
}

Description :-
As you can see in above example, when we pass null in m1() String version method got executed, since the child class methods gets more priority.

Nows lets take another example

	class Test
	{
		public void m1(StringBuffer sb)
		{
			System.out.println("String Buffer");
		}

		public void m1(String s)
		{
			System.out.println("String here");
		}

		public static void main(String[] args)
		{
			Test t = new Test();
			t.m1("Harsha"); // String version
			t.m1(new StringBuffer("Harsha")); //StringBuffer Version
			t.m1(null); // Compiler Error - reference to null is ambigious
		}
	}

Description :-
As we can notice, in the above example we will get compile time error when we try to pass null since both String and StringBuffer are subclasses of object.



3. In overloading method resolution is always taken care by compiler based on reference type. Runtime object wont play any role

you will definatily get one question from this in OCJP { 100% }

		class Animal
		{
		}

		class Monkey extends Animal
		{
		}

		class Test
		{
		   public void m1(Animal a)
			{
				System.out.println("Animal version");
			}

			public void m1(Monkey m)
			{
				System.out.println("Monkey version");
			}

			public static void main(String[] args)
			{
				Test t = new Test();
				Animal a = new Animal();
		        t.m1(a); //Animal Version
				Monkey m = new Monkey();
				t.m1(m); //Monkey version
				 a = new Monkey();
				t.m1(a); // Animal version
			}
		}

Discription :-
In last method even when we pass a Monkey object the output is “Animal version” since the reference type is of Animal and compiler only cares about reference type.