4.6 Creating Objects

Previous Index Next 


In Java primitive data types can be declared and the used. However object instances need to be declared and the instantiated before they can be used. The new operator is used to instantiate an object.

For example:

Integer myInt;

myInt = new Integer(0);
The declaration and instantiation can be collapsed into one line like this:
Integer myInt = new Integer(0);
When the new statement is called a special kind of method is called on the class to initialize the object. This method is called a constructor. A constructor method is declared without a ReturnType and it must have the same name as the class. A class can have more then one constructor provided that each constructor has a different parameter list.

If no constructor is specified for a class the Java compiler automatically builds a constructor that accepts no parameters. This constructor is called a no-args constructor.

As an example the Integer class has two constructors one that excepts a int and one that excepts a String. It does not have a no-args constructor. The Integer class can therefore be instantiated as follows:

Integer myInt1 = new Integer(10);     // declare and initialize an Integer class setting it value to 10 from an int

Integer myInt2 = new Integer("1234"); // declare and initialize an Integer class setting it's value to 1234 from a String
Constructors are covered in more detail later in the guide.



  1