Objects are created from a class blueprint and express a state and behaviour.
Creation of Objects
The following statements are used to create an object and assign it to a variable:
Point originOne = new Point(23, 94); Rectangle rectOne = new Rectangle(originOne, 100, 200); Rectangle rectTwo = new Rectangle(50, 100);
The first line creates an object of the Point class, and the second and third lines each create an object of the Rectangle class. Each of these statements has three parts:
- Declaration: The left sides of the assignments are all variable declarations that associate a variable name with an object type.
- Instantiation: The new keyword is a Java operator that creates the object.
- Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
If a new Point variable originTwo is declared, no new objects will be created without using the new keyword:
This notifies the compiler that you will use originTwo to refer to data whose type is Point but its value will be undetermined until an object is actually created and assigned to it. You must assign an object to originOne before you use it in your code. Otherwise, you will get an error:
originTwo = new Point(10, 20);
Once you've created an object, you probably want to use it for something. You may need to use the value of one of its fields, change one of its fields, or call one of its methods to perform an action.
Referencing an Object's Fields
Object fields are accessed by their unique name. If you reference the field inside the class use just the name:
System.out.println("Width and height are: " + width + ", " + height);
From outside the class use an object reference or expression, followed by the dot "." operator, followed by a simple field name. Keep in mind that this only works if the field is accessable from where its called:
Rectangle rect = new Rectangle(50, 100); System.out.println("Width and height are: " + rect.width + ", " + rect.height);
Calling an Object's Methods
You also use an object reference to invoke an object's method. Append the method's simple name to the object reference, with an intervening dot operator ".". Also, you provide, within enclosing parentheses, any arguments to the method. If the method does not require any arguments, use empty parentheses.
objectReference.methodName(argumentList); // method with arguments objectReference.methodName(); // method without arguments