Here's how it works in the near future:
Compilation time
- The compiler determines the required signature for the requested method.
- Once the signature is defined, the compiler starts looking for it in the class type
- If it finds a compatible candidate method with the required signature receipts, otherwise an error is returned
lead time
- At run time, the JVM starts looking for a candidate method with a signature as exactly defined at compile time.
- The search for the executable method actually begins with the real class of the object implementation (which may be a subclass of the type-class) and look at the entire hierarchy.
Your list is defined using a gadget type.
for (Gadget gadget : l) { gadget.switchon(); }
When you request gadget.switchon(); , the compiler will look for the switchon() method in the Gadget class, and, as there, the candidate’s signature is simply confirmed as switchon() .
At run time, the JVM will look for the switchon() method from the smartphone class , which is why it displays the correct message.
This is what happens in the second for-loop
DemoPersonnel p = new DemoPersonnel(); for (Gadget gadget : l) { p.demo(gadget); }
The signature in this case is intended for both demo(Gadget g) objects, therefore the demo(Gadget g) method is executed for both iterations.
Hope this helps!
jnardiello
source share