• 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

Assigning sub class reference to super class object

 
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Pls check this code:
==========================================
class Base{
void methodA(){
System.out.println("methodA");
}
}

class Sub extends Base{
void methodB(){
System.out.println("methodB");
}

public static void main(String a[]){
Base oBase = new Sub();
oBase.methodB(); //causing the error
}
}
===========================================
Here, even I have created base object, assigning the reference of Sub. Now why I am not able to call a methodB() which is exisitn in Sub class???
When I put the methodB() in Base class its workign fine.
 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey,
Consider this segment of code

public static void main(String a[]){
Base oBase = new Sub();
oBase.methodB(); //causing the error
}
}
Now, since oBase is declared to be a reference to an object of Base, all that the compiler knows is methodA() (even though u r assigning a child class reference which happens only at runtime) and hence the error.
To overcome this, one way would be to have a dummy method named methodB in base. Hope this would be helpful.
 
Ja vardhan
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sandeep- Thanks for your reply.
 
Ja vardhan
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sandeep- Thanks for your reply.
reply
    Bookmark Topic Watch Topic
  • New Topic