Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism using Interface and Classes

Is there any difference on the polymorphism coded below? Basically is there difference in the binding of the method calls?

Polymorphism Type 1:

class A
{
    public void method()
    {
        // do stuff
    }
}

class B extends A
{
    public void method()
    {
        // do other stuff
    }
}

Now I do stuff with B using A

A a =  new B();
a.method();

Polymorphism type 2:

public interface Command
{
    public void execute();
}

public class ReadCommand implements Command
{
    public void execute()
    {
        //do reading stuff
    }
}

public class WriteCommand implements Command
{
    public void execute()
    {
        //do writing stuff
    }
}

public class CommandFactory
{
    public static Command getCommand(String s)
    {
        if(s.equals("Read"))
        {
            return new ReadCommand();
        }
        if(s.equals("Write"))
        {
            return new WriteCommand();
        }

        return null;
    }
}

Now I use the command factory:

Command c = CommandFactory.getCommand("Read");
c.execute();

My question is : Is there any difference in the above two polymorphisms. I know both are examples of run time polymorphism, but is there any difference [with respect to binding of the methods], or any other difference for that matter?

like image 496
Swaranga Sarma Avatar asked Oct 25 '22 16:10

Swaranga Sarma


2 Answers

I guess there's one difference between

Command c = CommandFactory.getCommand("Read");

and

A a =  new B();

... in the first case, you have no option but to use the interface (or just Object) because the expression on right hand side of the assignment operator is of type Command.

In the second case, you're deliberately choosing to assign the result to a variable of type A, even though you could have written

B b = new B();

This is really just a difference in the design choices though - it doesn't affect how a call to c.execute() or a.execute() will actually behave.

like image 98
Jon Skeet Avatar answered Oct 27 '22 10:10

Jon Skeet


Your Polymorphism Type 1 and Polymorphism Type 2 is the same polymorphism :)

like image 42
dantuch Avatar answered Oct 27 '22 11:10

dantuch