Java: Constructors

Posted February 14, 2006 by William_Wilson in Java programming

This tutorial explains the use and creation of constructors.


*A constructor is used as an example with serializable.

A constructor is a method with the same name as the class in which it is defined and is automatically called with the operator new.

CODE example:
public class Constructor{
public static class Objects implements java.io.Serializable{
String text;
public Objects(){
text = “William. §”;
}
public Objects(String s){
text = s;
}
}
public static void main(String args[]){
//create an object initialized by the constructor
Objects o = new Objects();
System.out.println(o.text); //the output is William. § since that is the text provided in the default constructor.
//create another object initialized with text supplied
Objects o2 = new Objects(“Wilson”);
System.out.println(o2.text); //the text within the object o2 is Wilson since we supplied it
}
}

This example uses two different constructors in the same class Objects. This is possible only because the parameter list is different for the two constructors and is possible for any method. Thus the JVM determines which instance of the method to call based on the variables involved. In our case, one involves no parameters, and the other has a String.
This is known as method or function Overloading, when applying the same name to different operations.

Constructors are very useful when default values are wanted to initialize a newly created Object.

Questions/Comments: [email protected]
-William. § (marvin_gohan)

The Conversation

Follow the reactions below and share your own thoughts.