• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Object Reference

 
Greenhorn
Posts: 1
  • 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;
}
}

//Second code
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;
}
}
Output is 2 & 3 as the rule for accessing variables object ref is used and while assessing methods object is used(understandable) but if I change the code by removing method() in base as it is not being referenced by the object b, I get" method not found in class Base error" during compailing " Again If cast object b by changing line to System.out.println(((Subclass)b).method()); it will compaile and output 2 & 3 Can any body explain correctly
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because you are asking a "base" object to do what only a "subclass" object is capable of doing. The strength of polymorphism is that no matter what subclass you shove into the base class you know that it will without a doubt be able to accomplish any method that is in base. The opposite is not true.
Only when you clarified for the compiler that the thing actually in the "base" object was indeed a "subclass" by casting, was the compiler willing to go the extra step and look for the lower level methods.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic