Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question from Exam lab practice Exam 1 about polymorphism Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question from Exam lab practice Exam 1 about polymorphism" Watch "Question from Exam lab practice Exam 1 about polymorphism" New topic
Author

Question from Exam lab practice Exam 1 about polymorphism

Sammy Bill
Ranch Hand

Joined: Dec 29, 2008
Posts: 96


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

Joined: Dec 08, 2008
Posts: 26
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

Joined: Aug 29, 2008
Posts: 580

Polymorphism applies to instance methods only not to member variables.


SCJP 6
Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
Treimin Clark
Ranch Hand

Joined: Nov 12, 2008
Posts: 757
<please delete>
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question from Exam lab practice Exam 1 about polymorphism
 
Similar Threads
Question about System.out.println() in a non-void method
Question about System.out.print behavior
What is happening here? Devakas Practice exam 1 Q 11
what is this??? I m confused
strange behavior of overridden call