A Java object is a combination of data and procedures working on the available data. An object has a state and behavior. The state of an object is stored in fields (variables), while methods (functions) display the object's behavior. Objects are created from templates known as classes. In Java, an object is created using the keyword "new". Object is an instance of a class.
There are three steps to creating a Java object:
- Declaration of the object
- Instantiation of the object
- Initialization of the object
When a Java object is declared, a name is associated with that object. The object is instantiated so that memory space can be allocated. Initialization is the process of assigning a proper initial value to this allocated space. The properties of Java objects include:
- One can only interact with the object through its methods. Hence, internal details are hidden.
- When coding, an existing object may be reused.
- When a program's operation is hindered by a particular object, that object can be easily removed and replaced.
A new object t from the class "tree" is created using the following syntax:
Tree t = new Tree ().
Below example shows the implementation of class and object.
Method That Returns Value
Method That Takes Parameters
Passing by value
Actual parameter expressions that are passed to a method are evaluated and a value is derived. Then this value is stored in a location and then it becomes the formal parameter to the invoked method. This mechanism is called pass-by value and Java uses it.
Passing by Reference
We know that in C, we can pass arguments by reference using pointers, and same can be done in C++ using references. Java is pass by value and it is not possible to pass primitives by reference in Java. Also integer class is immutable in java and java objects are references that are passed by value. So an integer object points to the exact same object as in the caller and but no changes can be made to the object which gets reflected in the caller function.