Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assigning sub class reference to super class object

 
Ja vardhan
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.
 
Sandeep Prabhakar
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic