You are on page 1of 2

CSCI 1302: Computer Science II Fall 2018

Overriding Methods
Overloading vs. Overriding
In method overloading, we wrote variations of a method, passing different arguments to each. For example:

1 public static double computeAvg(int x, int y){
2 return (x + y) / 2.0;
3 }
4
5 public static double computeAvg(int x, int y, int z){
6 return (x + y + z) / 3.0;
7 }
8
9 public static double computeAvg(double x, double y){
10 return (x + y) / 2.0;
11 }


These three methods have the same name, computeAvg, but the number of the parameters is different (the first
has 2, the second has 3) or the data type of the parameters is different (the first and second have int parameters,
while the third has double).

In inheritance, we may need a variation of a superclass in our subclasses to make it more specialized. For
example, if we had the following Pet class:

1 public class Pet{
2 public void speak(){
3 System.out.println("Hello.");
4 }
5 public void exercise(){
6 System.out.println("Doing some activity");
7 }
8 }


and we had two subclasses, Dog and Fish, they would exercise differently, right? It wouldn’t make sense,
though, to make methods in each class with different names, it’s still exercise, it’s just implemented differently by
the different subclass objects, so we should just override it.

An overridden method, unlike an overloaded one, MUST have the same name AND the same number and or
type of parameters. Consider the Dog and Fish classes below.

-1-

1 public class Dog extends Pet{
2 public void exercise(){
3 System.out.println("My owner is taking me for a walk!");
4 }
5 }



1 public class Fish extends Pet{
2 public void exercise(){
3 System.out.println("Swimming around in my bowl!");
4 }
5 }


Notice that both methods are named exercise and that neither has a parameter, just like the one in the Pet
superclass, thereby overriding the method in the superclass. NOte that method overriding can only occur during
inheritance.

If a subclass overrides a superclass method, when doing that method call, the subclass version is used, otherwise,
the superclass’s version is used. Here’s an example.

1 public class OverridingDemo{
2 public static void main(String[] args){
3 Dog d = new Dog();
4 Fish f = new Fish();
5 d.speak();
6 d.exercise();
7 f.speak();
8 f.exercise();
9 }
10 }


Here’s the output:

Hello
My owner is taking me for a walk!
Hello
Swimming around in my bowl!

-2-

You might also like