wood burning stoves 2.0*
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

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 24183

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: http://aspose.com/file-tools
subject: Why the o/p is not what it is expected ?
Similar Threads
What will be the output?Why? - extension
confusion in the output
polymorphism Problem (tricky)