• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Issue with Rule Round-up Game

 
Sidharth Pallai
Ranch Hand
Posts: 134
Hibernate Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I didn't get the logic behind the output of this code i found in Rule Round-up Game, Question #159. The output is correct,but i've a doubt.

Though class B inherits method(),why it shouldn't access its own member variable x, rather than priting 10, why it prints 9.Can anyone explain.
 
Bill Cruise
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the object you're calling the method on is type A.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Bill Cruise:
Because the object you're calling the method on is type A.


Correct.

But even

new B().method();

would print 5. And *that* is because *fields* are *not* polymorphic, only methods are.
 
Sidharth Pallai
Ranch Hand
Posts: 134
Hibernate Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank Preuss,
But i didn't get idea of how fields being non-polymorphic.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The variable A.x and the variable B.x are different variables. Even though they have the same name, they're not related to each other, and a B object contains one of each. The code in method() knows that, when it is compiled, "x" means "A.x", and therefore, no matter how that method is called, it's the x in class A that will be used.

Compare your code to this version of class B:



This version prints "10", for two reasons. First, because we're using an instance of class B, not A. But as Ilja said, that wouldn't be enough with the original code, which still prints "5" even if you create an instance of B. In this version, instead of creating a new, separate variable, we just assign a new value to the existing one; and then method() sees that new version.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic