• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic