Polymorphism Concept Simplified in Java

0
52
Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Polymorphism in Java
Polymorphism in Java

Polymorphism in Java:

Java allows polymorphism in term of methods.Polymorphism means one definition and many different behaviors.It is polymorphism’s ability to take more than one form.An operation may exhibits different behaviors in different instance.The behaviors depends upon the types of data used in the operations. Encapsulation creates new data types by data and methods.Implementation hiding separates the interface from the implementation by making details private. Polymorphism deals with decoupling in terms of types. Inheritance allows the treatment of an object as its own type or its base type.This feature allows many types which are derived from main base class to be treated as if they were one type and a single piece of code to work on those different child classes equally. The polymorphic method call allows one type to express its distinction from another.similar type,as long as they are derived from the same base class(type).This difference is expresses through differences in behavior of the methods , we call through base class.In other word Polymorphism is a dynamic binding.  

an example:


class MyClass{
    public int x,y; 
    MyClass(int x,int y)
    {
        this.x=x;
        this.y=y;
    }
    float difference(int x,int y)
    {
        int dx=this.x-x;
        int dy=this.y-y;
        return (float)Math.sqrt(dx*dx+dy*dy);
    }
    float difference(MyClass mc)
    {
        return difference(mc.x,mc.y);
    }
}
class MyAnotherClass extends MyClass{
    int z;
    MyAnotherClass(int x,int y,int z)
    {
        super(x,y);
        this.z=z;
    }
    float difference(int x,int y,int z)
    {
        int dx=this.x-x;
        int dy=this.y-y;
        int dz=this.z-z;
        return (float)Math.sqrt(dx*dx+dy*dy+dz*dz);
    }
    float difference(MyAnotherClass mac)
    {
        return difference(mac.x,mac.y,mac.z);
    }
}
public class TestPoly{
    public static void main(String args[])
    {
        MyClass mc1=new MyClass(2,3);
        MyAnotherClass mac1=new MyAnotherClass(3,4,5);
        MyClass mc2=new MyClass(5,6);
        MyAnotherClass mac2=new MyAnotherClass(7,8,9);
        float d0=mc1.difference(0,0);
        float d1=mc1.difference(mc2);
        System.out.println("Difference between them"+d0);
        System.out.println("Difference between them"+d1);
        d0=mac1.difference(0,0,0);
        d1=mac2.difference(mac1);
        System.out.println("Difference between them"+d0);
        System.out.println("Difference between them"+d1);
        }
}
 

output of the code:
$javac TestPoly.java
$java -Xmx128M -Xms16M TestPoly
Difference between them3.6055512
Difference between them4.2426405
Difference between them7.071068
Difference between them6.928203

How method call Binding happens?

Polymorphism plays an important role in allowing objects having different internal structres to share the same external interface.A generic class of operations may be accessed in the same manner even though specific action associated with each operation may differ.

Connecting a method call to a method body is called binding.When binding is performed before the programming is run by compiler and linker, it is called early binding.But the issue with early binding is that compiler can not know the correct method call when it has an object handle.To resolve this we have to come up with late binding that is the binding occurs at runtime based on the type of the object. Late binding is also called dynamic binding or runtime binding.This is to help compiler/JRE to understand the type information that needs to be installed in the object itself.All method binding in java are late binding until it is a final. This means that we don’t have to make any decision about whether late binding will occur. JRE does that automatically.This is one of the main reason why final methods exists as it prevents anyone to override the method. So by final , it turns off the dynamic binding that is it tells compiler that dynamic binding is not necessary.A method call associated with a polymorphic reference depends on the dynamic type of that reference.

How the right method call happens?

As all binding of methods in java happen polymorphically via late- binding,we can always write our code to talk to the base class and know that all the derived class will work correctly using the same code.In this way,if we send a message to an object and let the object figure out the right thing to do.Three classes Circle,Square and Line could be used to represent the three types of shapes.These three classes have a common super class Shape to represent common features.

Shape
———
draw()
setColor()
erase()
———
        |
       v
———-
        |
      v
———-
       |
       v
Circle
———
draw()
setColor(Color newColor)
erase()
Square
———
draw()
setColor(Color newColor)
erase()
Line
———
draw()
setColor(Color newColor)
erase()

The implementation of setColor() method could be


class Shape{
Color color;
void setColor(Color newColor)
{
this.color=newColor;
redraw();
}
void draw()
{
}
}

The Shaoe class can have instance variables to represent the color,position,size etc.But for the draw() method each of these Shapes are drawn differently.


Class Circle extends Shape{
void draw(){}
}
Class Line extends Shape{
void draw(){}
}
Class Square extends Shape{
void draw(){}
}
 

Handles of each object needs to caste up the inheritance diagram. The upcasting could occur in the following manner-


Shape sCircle=new Circle();
Shape sSquare=new Square();
Shape sLine=new Line();
//general form
Shape myShape=new child();
 

Here the Circle object is created and resulting handle immediately assigned to a Shape.This looks error (assigning one type to other).But this is fine as Circle is a Shape by inheritance.So the compiler agrees with the statement and does not give any compilation error.So when we call one of the base class methods(which may been overridden in the derived classes)like-


sCircle.draw();
 

It is expected that the Shape’s draw(base class method) method is called as it is a Shape handle.The compiler won’t know anything else,but still Circle’s draw() method is called due to late binding(Polymorphism).

if myShape is a variable of type Shape it is called to refer to an object of any of the types,Circle,Sqaure,Line.
myShape.draw() when called,the draw method is actually calls the appropriate type of object to which myShape actually refers.Now for every instance of draw() if called,it could refer to the actual Object and calls the exact draw()method. In this way draw() is polymorphic.
Summary:
A method is said to be polymorphic if the action performed by the method depends on the actual type of the Object to which the method is applied.
Polymorphism means that different objects can respond to same message in a different way.The good point of polymorphism is that if a new class gets added (Say-Oval).It just needs to extends Shape and implement draw() method.With the same myShape.drwa() method we can implement Oval drawing.

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

LEAVE A REPLY

Please enter your comment!
Please enter your name here