• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding Polymorphism

 
chander shivdasani
Ranch Hand
Posts: 206
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jeevitesh Singh
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
chander shivdasani
Ranch Hand
Posts: 206
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everyone for your reply. I understood the concept well.
 
Rashmi Jaik
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic