Java dynamic, static casting -


import javax.swing.*;  public class toast {     static object[] objects = { new jbutton(),         new string("example"), new object() };      public static void main(string[] args) {         system.out.println( new count(objects) );         (object o : objects)             system.out.println(o);     } }   class count {     int b, s, o;     public count(object[] objects) {         (int i=0; i<objects.length; i++)             count(objects[i]);     }     public void count(jbutton x) { b++; }     public void count(string x) { s++; }     public void count(object x) { o++; }     public string tostring() {         return b + " : " + s + " : " + o + "\n";     } } 

above piece of code appears in form or other in past exam papers 1 of upcoming tests. idea of question gauge if understand polymorphism, dynamic , static casting. basic ideas of oo.

i put out think correct , if people able correct me or add points appreciated.

from can see in above code:

  • items upcast objects in object array every class in java technically inherits object class. why when count run there 3 objects not 1 jbutton, 1 string , 1 object.

  • when enhanced loop run tostring of object type e.g. example string , memory address of object (not sure jbutton print). done @ runtime known dynamic casting.

i cannot see other points relevant above bit of code.

the idea behind static cast , dynamic cast related moment type decision needs made. if needs made compiler it's static cast. if compiler postpones decision runtime it's dynamic cast.

so, first observation incorrect. upcast not explain count. objects not loose type compiler needs perform static cast decide method invoke , chooses count(object). there no dynamic dispatch in java means method called decided @ compile time.

you second observation incorrect. in use polymorphism. in java, methods invoked type of instance , not type in code. also, there no dynamic casting here. compiler can verify types. it's method invocation virtual that's not cast.

actually in example, don't see single case of dynamic casting. compiler can verify types. see dynamic casting when down casting , there no case of that.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -