wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Regarding Polymorphism Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Regarding Polymorphism" Watch "Regarding Polymorphism" New topic
Author

Regarding Polymorphism

chander shivdasani
Ranch Hand

Joined: Oct 09, 2007
Posts: 206

While practicing i just wrote one code to try polymorphism with Varibles. Here is the code


the output to the above code is 3. i was expecting it to be 8, since x refers to test1 object.

Kindly provide some inputs


Enjoy, Chander
SCJP 5, Oracle Certified PL/SQL Developer
Jeevitesh Singh
Greenhorn

Joined: Jun 19, 2008
Posts: 28
hi.....
overidding works for instance methods and only instance methos not with
instance variables or any other case....
and in your case value of x is called on the reference variable of the superclass..
that is why the ans 3 instead of 8..i hope i have made it clear.....
Sandhya Bhaskara
Greenhorn

Joined: Jun 29, 2005
Posts: 23
Polymorphism applies only to INSTANCE METHODS.

Reference type decides which class's instance variables are to be used.

Test x = new Test1();
x is of type Test(superclass) . So x.a refers to the instance variable in superclass(3)

If you change your code to
Test1 x = new Test1();
x.a refers to the instance variable in subclass Test1(8)


Sandhya Bhaskara<br />SCJP 1.4,SCWCD 1.4,SCBCD 1.3,SCJP 6
Mohammad Khan
Ranch Hand

Joined: Sep 23, 2008
Posts: 37
http://www.coderanch.com/t/270598/java-programmer-SCJP/certification/explanation-covariance
chander shivdasani
Ranch Hand

Joined: Oct 09, 2007
Posts: 206

Thanks everyone for your reply. I understood the concept well.
Rashmi Jaik
Ranch Hand

Joined: Oct 04, 2008
Posts: 50
The actual object type test1 only applies to instance methods.

For variables and static methods, the reference type applies.

So in this case: test x = new test2();

The reference type is test and the actual object type is test2.

We have to remember this runtime rule. Just thinking of the program's sequential execution is not sufficient.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Regarding Polymorphism