How to Use a Constructor in Java

A constructor in Java is a block of code similar to a method that’s called when an instance of an object is created. Here are the key differences between a constructor and a method:

  • A constructor doesn’t have a return type.

  • The name of the constructor must be the same as the name of the class.

  • Unlike methods, constructors are not considered members of a class.

  • A constructor is called automatically when a new instance of an object is created.

Here’s the basic format for coding a constructor:

public ClassName (parameter-list) [throws exception...]
{
    statements...
}

The public keyword indicates that other classes can access the constructor. ClassName must be the same as the name of the class that contains the constructor. You code the parameter list the same way that you code it for a method.

Notice also that a constructor can throw exceptions if it encounters situations that it can’t recover from.

A constructor allows you to provide initial values for class fields when you create the object. Suppose that you have a class named Actor that has fields named firstName and lastName. You can create a constructor for the Actor class:

public Actor(String first, String last)
{
    firstName = first;
    lastName = last;
}

Then you create an instance of the Actor class by calling this constructor:

Actor a = new Actor("Arnold", " Schwarzenegger");

A new Actor object for Arnold Schwarzenegger is created.

Like methods, constructors can be overloaded. In other words, you can provide more than one constructor for a class if each constructor has a unique signature. Here’s another constructor for the Actor class:

public Actor(String first, String last, boolean good)
{
    firstName = first;
    lastName = last;
    goodActor = good;
}

This constructor lets you create an Actor object with information besides the actor’s name:

Actor a = new Actor("Arnold", "Schwarzenegger", false);

If you do not provide a constructor for a class, Java will automatically create a default constructor that has no parameters and doesn’t initialize any fields. This default constructor is called if you specify the new keyword without passing parameters. For example:

Ball b = new Ball(); 

Here, a variable of type Ball is created by using the default constructor for the Ball class.

If you explicitly declare any constructors for a class, Java does not create a default constructor for the class. As a result, if you declare a constructor that accepts parameters and still want to have an empty constructor (with no parameters and no body), you must explicitly declare an empty constructor for the class.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com