The new operator instantiates a class by allocating memory for a new object of that type. It requires a single argument: a call to a constructor method. Constructor methods are special methods provided by each Java class that are responsible for initializing new objects of that type.
![]() | Note |
---|---|
The new operator creates the object, the constructor initializes it. |
The new operator returns a reference to the newly created object. This reference can be assigned to a variable of the appropriate type.
Rectangle rect = new Rectangle(0, 0, 100, 200);
There are two ways to change the state of an object:
Manipulate the object's variables directly;
Call one of the object's methods.
The second option is more object-oriented and safer because you manipulate the object's variables indirectly through its protective layer of methods rather than twiddling directly with them.
Manipulating an object's variables directly is often considered error-prone; you could potentially put the object into an inconsistent state.
To access an object's variables, simply append the variable name to an object reference with an intervening '.' (period).
objectReference.variable
Calling an object's method is similar to getting an object's variable. To call an object's method, simply append the method name to an object reference with an intervening '.' (period), and provide any arguments to the method within enclosing parentheses. If the method does not require any arguments, just use empty parentheses.
objectReference.methodName(argumentList);
or
objectReference.methodName();
Copyright © 1998-2009 Dilvan Moreira