Object

A typical Java program creates many objects, which as you know, interact by invoking methods. Through these object interactions, a program can carry out various tasks, such as implementing a GUI, running an animation, or sending and receiving information over a network. Once an object has completed the work for which it was created, its resources are recycled for use by other objects. An object or instance of a class can be created:

Within The Class

You can create an instance of a class in its main method.

From Another Class

An object also can be instantiated in the main method of another class.

Run The Application

Both of the above classes have same output. To run the classes; right click to each of them; select Run As -> Java Application.

Output

Creating Objects

Creating an object has three parts:

  • Declaration: a variable name with an object type is associated with the new created object.
  • 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.

Calling Object’s Methods

After creating object, you have to set value for fields by calling their setter methods:

Or simply call the constructor with 2 parameters for same result

Note: You don’t have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors.

In this example, we use a constructor with 2 parameter; so you have to provide a no-argument constructor in Human class in order to use this statement: