Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes overloading - basics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "overloading - basics" Watch "overloading - basics" New topic

overloading - basics

ARS Kumar
Ranch Hand

Joined: May 22, 2000
Posts: 108
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);

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.
ARS Kumar.

ARS Kumar, Sun Certified Programmer for Java 2 Platform
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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.
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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
I agree. Here's the link:
subject: overloading - basics
It's not a secret anymore!