Win a copy of Design for the Mind this week in the Design 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: 24208
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic