• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Question from Exam lab practice Exam 1 about polymorphism

 
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


the result was Sub1 2

isn't that polymorphism is applied only to methods and not instance fields?
shouldn't Greek ga=new Arabik();
System.out.print(ga.i+" "+ga.getI());
print i from Greek and getI() from Arabik?


can someone explain why it prints Sub1 2?

Thanks
 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Oussama! I'll explain to you step-by-step how it gets "Sub1 2".

1. It instantiates an object of Greek type to Arabik polymorphic type in the runtime and assigned it to variable a.
2. It uses static method System.out.print() to print the value of i and getI() method, but before the print() method executes
it must first evaluate the getI() method in order to get the returned value of it that's line 22 is executed to print "Sub".
3. After line 22 is executed it return the value of Arabik.i which is 2 because Arabik class is the runtime obect of the variable a and it calls
its own i variable.
4. After it returning the value of 2, the print() method can now append ga.i which which has a value of 1 because its declared type is Greek
so it will call its types instance variable i.
5. value 1 will be concatenated to value 2 which will give us "1 2". This value will be appended to "Sub" string because the print() method doesn't
produce another line.

> Sub1 2
 
Ranch Hand
Posts: 580
Eclipse IDE
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Polymorphism applies to instance methods only not to member variables.

 
Ranch Hand
Posts: 757
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
<please delete>
 
please buy my thing and then I'll have more money:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic