简体   繁体   中英

Is this really Dynamic Polymorphism? What information is available to the compiler when we use a new opearator to instantiate a class?

It us generally said that when we do Set<Stamp> stamps= new HashSet<Stamp>(); stamps.add(new Stamp()); Set<Stamp> stamps= new HashSet<Stamp>(); stamps.add(new Stamp()); it is an example of dynamic polymorphism . I find this confusing because when the code gets compiled the compiler knows ahead of time that stamps refers to an Object of type HashSet<Stamp> . So it knows how to deal with the add method during compile time only . How can this be an example of dynamic polymorphism? The basic difference between using the new operator and Class.forName().getInstance() is that in the former case the compiler knows the type of Class that we are trying to instantiate ?

Compiler knows that stamps is Set<Stamp> because you declared it so. It also knows that on one particular line you assign it to new HashSet<Stamp>() . Later you may reassign it to new MyOwnSetImpl<Stamp>() or anything that implements Set<Stamp> . You may have complex logic, that assigns stamps to one implementation of Set<Stamps> or another depending on user input. You can even debug your code, put a breakpoint before you call .add() and manually change stamps value to something that is not in your code during compilation. All these is perfectly valid. To allow you to do it, .add() is called dynamically - it will call .add() method of the class stamps is instance of, and it will find out what that class is in runtime.

No, it only "knows" that stamp is a Set . It doesn't know that it is a HashSet after it is constructed.

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