SCJP Certification

Sun Certified Java Programmer Certification exam essentials

November 2nd, 2009

What is a constructor?

Java Facts, by Daisy Williams.

A constructor provides a convenient way to initialize a newly created object at the time of its creation. A constructor is automatically called emmediately after the creation of a new object, but before the new operator completes. All Java classes must have at least one constructor, either explicitly declared in the class or an implicit default constructor. They are typically used to create an object that is an instance of a class. It is written by using the following general syntax:

[access modifier] class name([formal parameter list]) [throws clause] {
// Body of the constructor
}

where, the elements within square brackets are optional.

The following rules are followed before writing a constructor for a class:

  1. It uses the name of the class in which it is defined.
  2. A constructor is always written without an explicit return type, not even void. This is because the implicit return type of a class constructor is the class itself.
  3. Only accessibility modifiers can be used to declared a constructor. Unlike methods, a constructor cannot be declared as abstract, static, final, native, strictfp, or synchronized.

The following is an example of a constructor:

class Book{
String name;
String author;
Rectangle(String str1, String str2){
// more code
}
}

Share

Back Top

Responses to “What is a constructor?”

Comments (0) Trackbacks (1) Leave a comment Trackback url
  1. No comments yet.
  1. Constructors? | SCJP Certification (,November 17, 2009)

    [...] a constructor has a call to this(), the compiler will know that the constructor is not using the call to super(). [...]

Leave a Reply

Your email address will not be published. Required fields are marked *

*