Communication Between Two Classes

In java we can call the members of one class from another class by creating an object. It is useful when we need to use common code in every class again and again.

This is called communication between two classes and can be done in more than one way. You can also say that these objects can talk to each other. One object sends a message to which the other object replies, or returns a value. They call each other’s methods.


Let's say we have two developers, ’Kiran’ and ’Sachin’. Their manager asked Kiran to write code for a sum of two numbers, and sachin to write a code for avg.

Both of them started to write the code in their own ways.
Kiran wrote as below:


Sachin wrote as below:


Now, when they submit their code to the manager, he will say that Kiran wrote the code properly but not Sachin. Why that is so?

The reason is that Sachin wrote an additional logic again even though Kiran had written it earlier.
Hence, it was a waste of time since no reusability feature is used. We can't write logic twice. And since it had already been written by Kiran, Sachin should have used the former’s logic instead of repeating it.

Now Sachin rewrites his code as shown below:


In the industry, a single person cannot write the whole logic.
Because it is a mutual effort, we always have to reuse functionalities of each other. I will explain step by step what has happened here.

    SumLogic sl = new SumLogic();

Here we have created an object of class SumLogic. It means that we are trying to load SumLogic class by using a keyword called ‘new’.

The memory stores all members of class SumLogic [method sum] and s1 knows about address of that location.

We can say that s1 is eligible to call every thing [members like sum] of SumLogic class. In java, to call members by address we use the dot operator.

Like s1.sum(), we need to take care while doing this and the parameters should match the method, not just the name of method. In this case,int a and int b. See below for reference.

    s1.sum (34, 67);

The parameter sequence also matters if we write

    s1.sum (34,"java");

It is wrong because the second parameter must be type of ‘int’, we can't specify String here. It will show the error, “sum is not found in class SumLogic”.

sum() method of SumLogic class returns int. Now, its class AvgLogic has a choice whether to take that back or not. Even if we write

    s1.sum (34, 67);   // it's correct.
    int xx= s1.sum(34,67);
    

In the above case,we get the output of the method sum and stored in the xx variable.We can do anything with this variable after that, including addition,subtraction and any arithmetic operation.

    int xx= s1.sum(34,67); 
    int y = xx+89;   // possible