Java overloading vs overriding

user69514 picture user69514 · May 8, 2009 · Viewed 77.4k times · Source

Hi I just want to make sure I have these concepts right. Overloading in java means that you can have a constructor or a method with different number of arguments or different data types. i.e

public void setValue(){
   this.value = 0;
}
public void setValue(int v){
   this.value = v;
}

How about this method? Would it still be considered overloading since it's returning a different data type?

public int setValue(){
   return this.value;
}

Second question is: what is overriding in java? Does it relate to inheritance. Let's I have the following:

public class Vehicle{
  double basePrice = 20000;
  //constructor defined
  public double getPrice(){
     return basePrice;
   }
}

public class Truck extends Vehicle{
  double truckPrice = 14000;
  //constructor defined
  public double getPrice(){
     return truckPrice;
   }
}

So now let's say I have the following

Truck truck = new Truck();

if I call

truck.super.getPrice()

this would return the price from the Vehicle class, 20,000

if I call

truck.getPrice()

this would return the price in the truck class, 14,000

Is my knowledge correct for both questions?

Answer

Eddie picture Eddie · May 8, 2009

You are basically correct. Overloading is having multiple methods in a single class where the method has the same name. However, the return value is not seen as part of the signature of the method. Thus, you cannot overload a method by changing only the return value. You cannot have the following code, from your example:

public void setValue() {
   this.value = 0;
}

public int setValue() {
   return this.value;
}

This will fail to compile.

As Rob identified, I believe you mean overriding, and you have that correct. Note with overriding, you cannot change the return type. As of Java 5, you can return a derived type of what the base class method returned. Before Java 5, it must be the identical type. That is, you cannot do the below until Java 5 and later:

public class AnimalNoise {}
public class Miaw extends AnimalNoise {}

public class Animal {
    public AnimalNoise makeNoise() {
        return new AnimalNoise();
    }
}

public class Cat extends Animal {
    public Miaw makeNoise() {
        return new Miaw ();
    }
}

However, even in Java 5 and later, you cannot do the following:

public class Animal {
    public String makeNoise() {
        return "silence";
    }
}

public class Cat extends Animal {
    public Miaw makeNoise() {
        return new Miaw ();
    }
}
public class Miaw {}

Finally, a big difference between overloading and overriding that is often overlooked is that overloading is decided at compile time and overriding is decided at runtime. This catches many people by surprise when they expect overloading to be decided at runtime.