Initializing an Object

The classes can provide one or more constructors to initialize a new object of that type.
We can recognize a class’s constructors because they have the same name as the class and have no return type.

Here are the declarations for Rectangle’s constructors:
public Rectangle(Point p)
public Rectangle(int w, int h)
public Rectangle(Point p, int w, int h)
public Rectangle()

If a class has multiple constructors, they all have the same name but a different number of arguments or different typed arguments.

The compiler differentiates the constructors, and knows which one to call, depending on the arguments.

Using Objects
Objects give us two ways to do these things:

1. Manipulate or inspect its variables.
2. Call its methods.

Java provides an access control mechanism whereby classes can restrict or allow access to its variables and methods.

A class should protect variables against direct manipulation by other objects if those manipulations could endanger the object’s state. State changes should then be affected and therefore controlled by method calls.

Scroll to Top