• 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

subclass

 
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class test{
public static void main(String [] args){
Base b = new Subclass();
System.out.println(b.x);
System.out.println(b.method());
}
}

class Base{
int x = 2;
int method(){
return x;
}
}

class Subclass extends Base{
int x = 3;
int method(){
return x;
}
}


Can anyone explain the output??
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Instance methods are overridden.

Instance variables are hidden.

The type of the reference will determine which instance variable is used.

The run-time type of the object will determine which instance method is called.
 
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Keith is exactly right, but I don't know if he answered your question.

The output will be:

2
3

Polymorphism works for (properly overridden) methods, but not for instance variables. In theory, Java (or C++) could (with a bit of work) support polymorphism for instance variables. But they don't. And there aren't any serious reasons that they should. If you want an instance variable to behave polymorphically, you can change the variable to a "variable-like" method. For example, the following "variable-like" method can be overridden:

int x() { return 3; }
[ July 11, 2006: Message edited by: Douglas Chorpita ]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic