File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question from Exam lab practice Exam 1 about polymorphism

 
Sammy Bill
Ranch Hand
Posts: 96
  • 0
  • Mark post as helpful
  • send pies
  • 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
 
alex sandoval
Greenhorn
Posts: 26
  • 0
  • Mark post as helpful
  • send pies
  • 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
 
James Tharakan
Ranch Hand
Posts: 580
Eclipse IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Polymorphism applies to instance methods only not to member variables.

 
Treimin Clark
Ranch Hand
Posts: 757
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<please delete>
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic