Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

overloaded methods in derived class

 
william kane
Ranch Hand
Posts: 260
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class BaseClass{
public methodA(Object a){
System.out.println("base class called");
}
}
class DerivedClass extends BaseClass{
public methodA(String a){
System.out.prinltn("derived class called");
}
public static void main(String args[]){
BaseClass bc=new DerivedClass();
DerivedClass dc=new DerivedClass();
bc.methodA("hello");
dc.methodA("hello");
}
In the code shown above the derived class implenetation is never called either using a base calss refernce of derived class reference.
Should not no compiler object to such a code???
Or is there a way of invoking the derived classes implementation?
thanks
william
 
Argm Mastoi
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I think that when u overload a method in a derived class. and call the method through the object of derived class from outside, the method in base class is first called. so if the parameter suits then method of base calss executes. so try changing the type of parameter :roll: its only my opinion, i might be wrong.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
A couple of notes...
1. Your code won't compile. This will:

The output is not what you said it would be.
2. I recommend reading How My Dog Learned Polymorphism.
Good Luck
 
william kane
Ranch Hand
Posts: 260
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thansk
but thats the whole point, i donot want to change the parameter.All that i want to know is why is the compiler allowing code that can never be accessed to get compiled.Again is there a way to access it?
It can object to it as in the case of expections where ,when u try to catch a derived class of exception after catching the base class the compiler objects
william
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess I don't understand the question. When I compile your code (after adding "void" as return type to the methods):

I get the output:

base class called
derived class called

What do you mean by, "In the code shown above the derived class implenetation is never called"?
 
william kane
Ranch Hand
Posts: 260
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I profusely apologise for the time and effort wasted due to error on my side.
Will try not repeat in future
sorry once again
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic