By Tony Bevis on Sunday, 08 October 2023
Category: Java

Java programming course: 3.2 Method overloading

In the previous lesson you learnt about using classes and methods.

Method overloading

The Animal class currently defines a constructor which requires three argument values to be supplied (for the name, gender and age), and if when you invoke this constructor you supply the wrong number or the wrong type, the compiler will give you an error message.

You may consider that it would be useful for client objects to create newly born animal objects (i.e., whose age would be zero) without having to specify the third argument value, purely as a matter of convenience. Add the following constructor definition above the existing constructor in the Animal class:

Note the following:

Defining more than one constructor within a class is known as constructor overloading and is a common technique that allows client objects more flexibility in how they instantiate objects of your class. For example, to create a new-born animal you can now use either of the following two approaches, whichever is most convenient:

It is also possible to overload methods. For example, some animals may have a nickname, but instead of defining a separate instance variable for these odd cases you could instead overload the setName() method so that in addition to the current one which requires one String argument you define a second one which requires two:

Note the following:


Try the following statements in the VirtualZoo class:

The output from the above should show:

In the next lesson you will learn about inheritance.

Lesson 3.3 Inheritance

Related Posts

Leave Comments