Skip to content

Overloading constructors

September 1, 2011

In OOP, it is a common technique to overload a method.  Overloading means defining the method multiple times but with a different method signature.  By doing this, you can create different behavior and help prevent errors from occurring when the object is being used.  A common method to overload is the constructor method, which is the method automatically called when an object is created. By overloading the constructor method, you can create different states of your objects upon creation. For example:

In our Zombie class, we have a constructor method that requires 3 parameters to be passed in.

public Zombie(int s, int d, String n){
speed = s;
damage = d;
name = n;
}

This constructor method would automatically be called when an object is created from the class, like

Zombie joe = new Zombie(5,8,”joe”);

If the object were called without the correct parameters, like:

Zombie joe = new Zombie(8,”joe”);

Zombie joe = new Zombie(5,8);

Zombie joe = new Zombie();

Each call would fail, since we are not matching the required method signature.

A better way would be to overload the constructor like this, for example:

//constructor(s) – overloaded – polymorphic behavior
public Zombie(int s, int d, String n){
speed = s;
damage = d;
name = n;
}
public Zombie(){
speed = 1;
damage = 1;
name = “willie”;
}
public Zombie(int s, int d){
speed = s;
damage = d;
name = “willie”;
}

Depending on how the object is created and what parameters are passed in  controls which method is executed.

If you create an object like this:

Zombie joe = new Zombie(5,8,”joe”);  // method   public Zombie(int s, int d, String n) is called

Zombie joe = new Zombie(); // method  public Zombie() is called

Zombie joe = new Zombie(5,8); // method public Zombie(int s, int d) is called

This way, our object creation calls do not fail.  We get default state data if we call without parameters and we get specific state data if we call with parameter data.

This behavior, a different method called depending on how it is called,  illustrates polymorphism.

Advertisements

From → Java

One Comment
  1. Good post! Another tip that some people may benefit from with regards to constructors. Exposing just protected and private constructors allows you to control how the class can be instantiated. This is very useful when implementing certain design patterns like singletons; you can prevent the class from being instantiated elsewhere.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: