What is the benefit of Dynamic Polymorphism in Java?

别说谁变了你拦得住时间么 提交于 2021-02-18 08:47:05

问题


I am studying up on my Java Programming and Object Oriented Programming. I keep getting hung up on what the benefit of Dynamic Polymorphism is?

Take a look at my sample program below. Why would I use example 1 over example 2?

class SuperHero {
    private String power = ("Generic Power");
    public void useSuperPower() {
        System.out.println(power);
    }
}
class Spiderman extends SuperHero {
    private String power = ("Web sling!");
    public void useSuperPower() {
       System.out.println(power);
   }
}

class Wolverine extends SuperHero {
    private String power = ("Hack and Slash!");
    public void useSuperPower() {
        System.out.println(power);
    }
}

class main {
    public static void main (String args[]) {
        //example 1
        SuperHero hero = new SuperHero();
        SuperHero hero1 = new Spiderman();
        SuperHero hero2 = new Wolverine();

        hero.useSuperPower();
        hero1.useSuperPower();
        hero2.useSuperPower();


        //example 2
        Spiderman test = new Spiderman();
        Wolverine test2 = new Wolverine();

        test.useSuperPower();
        test2.useSuperPower();
    }
}

回答1:


The easiest example of when dynamic polymorphism is powerful is in collections. We can collect objects of different classes together, and use them all the same, so long as they all share a single parent interface. For instance:

List<SuperHero> avengers = new ArrayList<>();
avengers.add(new Spiderman());
avengers.add(new Wolverine());

System.out.println("Avengers Assemble!");
for(SuperHero hero : avengers){
    hero.useSuperPower();
}

It also allows for APIs to be very flexible. We can create methods which expect one interface, but later on pass them an object of a child type, without having to recreate that method. For instance:

public void usePower(SuperHero hero){
    hero.useSuperPower();
}

Here, we can call this method with object which extends SuperHero. (That example is a bit lame, since we could just call the useSuperPower() method directly, but hopefully you get the point.)

Basically, polymorphism allows us to create classes which all do the same thing, but do it differently, and then use them (almost) interchangeably.




回答2:


You'll probably never use example 1 directly. HOWEVER, you may end up in example 1 anyways (and hence Dynamic Polymorphism has value).

Let's say the two of us are coding a game together, and you've written the superhero hirearchy as you have in the question. Over on my side, I've written a class called JusticeLeagueScheduler with the method:

public JusticeLeagueScheduler {
    public static Superhero getAvaiableHero() {
        // ...
    }
}

Which allows you to get access to a superhero who can help save the day. Furthermore, suppose that the method getAvailableHero() is absurdly long, as it needs to take into account how often each superhero has been used, Logan's current BAC, Peter Parker's school schedule, etc etc etc.

When you call that method, you'll do so like this:

SuperHero superhero = JusticeLeagueScheduler.getAvailableHero();

At this point, you have no idea which hero you have, only that it is an instance or subclass of class SuperHero. Thus, you are in the situation in example 1. You can't call Wolverine methods on superhero, because it might be Wolverine, but it also might not be. You can call only methods defined by class SuperHero (or its parent type Object) on superhero.

However, it will still be the instance it is. If my method returns a Wolverine instance to you, and you call userSuperPower(), you will get "Hack and Slash", even though you couldn't have predicted that beforehand.




回答3:


In example 1, hero, hero1 and hero2 are all of type SuperHero. When you use the same method on different SuperHero objects, they behave in different manner. That is polymorphism.

However, in example 2, hero, hero1 and hero2 are all of different types. So, the example doesn't demonstrate polymorphism.




回答4:


Yes, you are saving yourself time and saving yourself code.

Polymorphism in Java

Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.

If you overload static method in java, it is the example of compile time polymorphism. Here, we will focus on runtime polymorphism in java.

Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Now let's take an example where you will need to convert one Spiderman object to SuperHero class, would you be able to do so if you instantiate without dynamic polymorphism. Answer is no.

Read more about Collection API and you will know why we need Dynamic Polymorphism.

Read this answer to understand the concept.

So, if you do the following:

SuperHero hero1 = new Spiderman();
SuperHero hero2 = new Wolverine();

You can also do:

SuperHero hero3 = new Spiderman();
hero3 =(Superhero) hero2;

Which you won't be able to do if you don't apply polymorphism.



来源:https://stackoverflow.com/questions/41496803/what-is-the-benefit-of-dynamic-polymorphism-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!