Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
faisal usmani
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic