This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Originally posted by Bill Cruise: Because the object you're calling the method on is type A.
would print 5. And *that* is because *fields* are *not* polymorphic, only methods are.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
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.