![]() ![]() ![]() ![]() |
Objects, Classes, and Interfaces |
In Java, you create an object by creating an instance of a class or, in other words, instantiating a class. To create a new object, use Java'snew
operator. Here's an example using thenew
operator to create a Rectangle object (Rectangle is a class in the java.awt package).Thenew Rectangle(0, 0, 100, 200);new
operator requires a single operand--a call to a constructor method. In the previous example,Rectangle(0, 0, 100, 200)
is a call to a constructor for the Rectangle class.Constructors are special methods provided by every Java class allowing programmers to create and initialize objects of that type. The
new
statement shown above initializes the new Rectangle object to be located at the origin (0, 0) with a width of 100 and a height of 200.Constructors have the same name as the class and, because Java supports method name overloading, a class can have any number of constructors. Like other overloaded methods, constructors are differentiated from one another by the number and type of their arguments.
For example, the Rectangle class in the java.awt package provides several different constructors, each of which requires a different number of arguments, and different types of arguments from which the new Rectangle object will get its initial state.
Typically, a constructor uses its arguments to initialize the new object's state. So, when creating an object, you should choose the constructor whose arguments best reflected how you wanted to initialize the new object. Here are the constructor signatures from the java.awt.Rectangle class:
The first constructor initializes a new Rectangle to some reasonable default, the second constructor initializes the new Rectangle with the specified width and height, the third constructor initializes the new Rectangle at the specified position and with the specified width and height, and so on.public Rectangle() public Rectangle(intValue, intValue) public Rectangle(intValue, intValue, intValue, intValue) public Rectangle(DimensionObject) public Rectangle(PointObject) public Rectangle(PointObject, DimensionObject)Based on the number and type of the arguments that you pass into the constructor, the compiler can determine which constructor to use. Thus the compiler knows that when you write
it should use the constructor that requires a four integer arguments, and when you writenew Rectangle(0, 0, 100, 200);it should use the constructor that requires one Point object argument and one Dimension object argument.new Rectangle(myPointObj, myDimensionObj);The
new
operator returns a reference to the newly created object. Typically, your program will assign the return value of thenew
operator to a variable so that you can use the object later. The variable must be of the same type as the object or one of its superclasses.Rectangle rect = new Rectangle(0, 0, 100, 200);
![]() ![]() ![]() ![]() |
Objects, Classes, and Interfaces |