File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
Author

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();
System.out.println(z.a);
z.display();
}
}


class A
{
int a=10;


void display()
{
System.out.println("base");
}
}

class B extends A
{
int a=20;


void display()
{
System.out.println("derived");
}
}

output::
10
derived
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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 ?