Creating Objects and Calling Methods in Java

In this class, We discuss Creating Objects and Calling Methods in Java.

The reader should have Intuition in Class and Object. Click Here

We take an example and understand how to create an object and call methods.

Example:

The below diagram shows the complete code.

The example has two classes.

The first class name is “firstexample”.

The second class name is “test.”

The file name and second class name are the same.

In the test class, we have a main method.

The main method is static.

The execution starts from the main method.

The line firstExample ob = new firstExample() is used to create an object for the class “firstExample.”

“ob” is called a reference variable.

The keyword new is used to create a memory allocation to the class.

Once the memory is created, we can use the methods present in the class.

How is memory allocated to objects and methods discussed in our next class?

“ob. add(1,5)” is used to call the add method in class “firstExample”.

The execution moves from the main method to add method.

After completion of add method, the execution continues in the main method.

When we call the mult method, we use variable z to store the return value.

The value z is displayed in the last line of code.