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

overloading - basics

 
ARS Kumar
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am little bit again ! This time please look at the following code
class Vehicle {

protected int overloadtrial(int r, boolean c) {
System.out.println("overloadtrial - In Vehicle");
return 0;
}
}
class Car extends Vehicle{
public boolean overloadtrial(boolean c, int a) {
System.out.println("overloadtrial - In Car");
return false;
}
}
public class OverloadTest {
public static void main (String args[]) {

int test1;
boolean test2;
boolean test3;

Vehicle Veh1 = new Vehicle();
Vehicle Veh2 = new Car();
Car Car1 = new Car();
test1 = Veh1.overloadtrial(0,false);
test2 = Veh2.overloadtrial(false,0);test3 = Car1.overloadtrial(false,0);
System.out.println("Done");

}
}
Why can't I invoke the public boolean overloadtrial(boolean c, int a) from class Car like Veh2.overloadtrial(false,0) ? If I change the return type and reverse the argument list this code will work.
That means when I say
Vehicle Veh2 = new Car();
test2 = Veh2.overloadtrial(0,false);
Veh2 is NOT having an instance of Car ???
Any help will be really appreciated.
Thanks
ARS Kumar.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ARS Kumar,
It appears from your example that you are trying to use polymorphism. To get polymorphic operation when calling a method, the method must be a member of the base class as well as the derived classed involved. Let me explain in the context of your example.
Your base class is vehicle and derived class is car. So to get polymorphic operation when calling your method overloadtrial, you have to override the method. What you have done is overloaded. If you override the method in class car and run your program, it should run without problems.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
please note that the sequence of the parameters is important for overriding example the method
x(int i, boolean j) is not the same as x(boolean j, int i)
also note that return types are not considered for overriding but the compiler will scream if the return types are different
Rahul
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic