简体   繁体   中英

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?

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.

您的Polymorphism Type 1Polymorphism Type 2是相同的多态性:)

With respect to runtime behavior there is no different . But

The difference is with the compilation . ie

In 1st Type as you are using the direct class references you need both the classes to be present at the compile time.

But With 2nd type the classes are required only at the runtime.

No difference in binding (runtime). Type 1 is tightly coupled whereas type 2 is loosely coupled, makes a difference in compiling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM