Thursday, July 3, 2008

Constructor Methods

A constructor method is a method that creates an object. To create the object, it uses the class as a sort of blueprint for what member variables the object has, what instance methods, and so on.

The name of a constructor method is the same as the name of the class. For example, if we have a class named Dragon its constructor will be named Dragon as well:
public class Dragon{

  public Dragon(){
    super();
  }
}

There are a couple of things to notice here. One is that, unlike a regular method, the first character is upper-case, just like the class name. The constructor name must exactly match the class name. While it is only a convention that classes (and therefore, their constructor methods) start with a capital letter, it is an iron-clad requirement that the constructor name match the class name.

The other thing you'll want to notice is that there's no type given in the method declaration. A normal method (called an instance method, if we want to get formal) has a type provided in its declaration, just as a variable has a type in its declaration:
public void dragon(){ }    // Instance Method.
public int dragonCount;    // Instance Variable.
public class Dragon{ }    // Class.
public Dragon(){ }    // Constructor.
In the constructor's declaration, there's a scope called out (public) but no type. This is because, as a constructor for the object, it will be returning an object of the type it is a constructor for. OK, that sounds worse than it is. Let's try again...

A Dragon constructor returns a Dragon object. A String constructor returns a String object. That's what it constructs, so that's what it returns. Declaring a type would be redundant:
public Dragon Dragon(){ }    // This is NOT correct code, just an example of silliness!

A Subtle Error

If you accidentally have a typo in your program that results in your class and constructor having different names, the compiler will complain that you've got a method without a type declaration. You'll look at the code and say "Hey! That's a constructor. It doesn't need a type declaration! What is my compiler smoking?"
public class Dragon{

public Dragin(){
super();
}
}

Dragon.java:3: invalid method declaration; return type required
public Dragin(){
^
1 error

What's happening here is that the compiler sees that the name of the method is different from the name of the class. Aha, it says, this isn't a constructor since it doesn't have the same name as the class. So it must be an instance method. Hey, instance methods need a type! There's no type! Then it prints the error message.

Note that spelling errors include capitalization. So having a class named Dragon with a constructor called dragon() would cause the same error.

For more about constructor methods, see Multiple Constructor Methods.
StumbleUpon