Polymorphism using the interface and classes

Is there any difference in the polymorphism encoded below? Basically, is there a difference in binding 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 things with B using A

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

Type of polymorphism 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 factory command:

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

My question is: is there a difference in the above two polymorphisms. I know that both are examples of run-time polymorphism, but is there a difference [regarding method bindings] or any other difference in this regard?

+4
source share
4 answers

I assume that there is 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 the right side of the assignment operator is of type Command .

In the second case, you intentionally assign the result to a variable of type A , although you could write

 B b = new B(); 

Actually, this is simply the difference in the choice of design - it does not affect how the call to c.execute() or a.execute() .

+2
source

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

+1
source

Regarding runtime behavior , there are no different ones . But

The difference is compilation . i.e

In the first type, since you use direct class references, you need both classes that will be present at compile time.

But with the second type, classes are only required at runtime.

0
source

No difference in binding (runtime). Type 1 is tightly connected, while type 2 is loosely coupled; it is important for compilation.

0
source

Source: https://habr.com/ru/post/1344582/


All Articles