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.
The moose likes Beginning Java and the fly likes Why the o/p is not what it is expected ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why the o/p is not what it is expected ? " Watch "Why the o/p is not what it is expected ? " New topic

Why the o/p is not what it is expected ?

faisal usmani
Ranch Hand

Joined: Jan 14, 2006
Posts: 139
Why output is (10 dervied) and not (20 derived)???

class Par
public static void main(String args[])
A z = new B();

class A
int a=10;

void display()

class B extends A
int a=20;

void display()

Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24189

Because variables aren't polymorphic the way methods are. You can't "override a variable". In main, you've got a reference to class A, and you ask for the "a" variable, so you get the "a" variable of class A. There's no special relationship between the two "a" variables as there is between the two "display" methods.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: Why the o/p is not what it is expected ?
It's not a secret anymore!