Win a copy of Mastering Corda: Blockchain for Java Developers this week in the Cloud/Virtualization forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Jj Roberts
  • Carey Brown
Bartenders:
  • salvin francis
  • Frits Walraven
  • Piet Souris

Assigning sub class reference to super class object

 
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • Quote
  • Report post to moderator
Sandeep- Thanks for your reply.
 
Ja vardhan
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sandeep- Thanks for your reply.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic