Overloading Methods and Constructors | Java

What is overloading?

Overloading is the term used when more than one method exists with the same name. It does not matter if the methods exist in the same class, or if one or both methods exist in the parent or child classes.

The compiler differentiates between the two methods using the methods parameters, specifically the order and the data types of the parameters. Therefore you could have two methods with the same name and two parameters as long as the data types were different or the same data types but in a different order.

Constructors are similar to methods except they do not have a return type and are used for setting the values of our instance variables when we initiate the object. Constructors are called using the new keyword from within our code.

Constructors can also be overloaded in the same way as methods and are very helpful for initialising our object with data we pass in or with default values if we do not currently have the data to pass to our constructor.

Here is an example of overloading constructors. We have the options to pass two parameters as strings to the constructor, in this instance the name and address which will then assign the appropriate values to the relevant variables within our class.

Our other option is to pass no parameters to the constructor which in turn would call our main constructor with the two parameters “unknown” for both name and address.

public class Overloading
{
    private String name;
    private String address;

    // The constructor we would like to use if we know
    //the customers name and address
    public Overloading (String newName, String newAddress)
    {
        name = newName;
        address = newAddress;

    }

    //set default values for name and address if these
    //details are unknown to us at this point
    public Overloading ()
    {
        //pass Unknown for our name and address
        //to our main constructor
        this("Unknown", "Unknown");
    }
}

It is possible to have a class without a constructor at all as java will handle the initialisation of the object for us but it is not possible to pass parameters with the wrong data type or in the wrong order to the constructor as this would cause a compile error.

Comments

Permalink

very impressive..

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.