Bogdan
Bogdan

Reputation: 673

Java: Why a method called inside another method is called automatically with the current calling object in Java?

I have a method that return a boolean value if two object (arrays) have the same average. Inside the body of the method a 3rd party method is called ( average() ). When the 3rd party method is called , it's called automatically for the current object. Why is that?

boolean sameAvg(GenBoundedType<?> i){
        if(average() == i.average()) {
            return true;
        }
        else return false;
    }

It's redundant to call average with "this": if(this.average() == i.average()) because the calling is automatically made for the current calling object. If somebody of good will can explain why the average() method inside sameAvg() is called automatically for the current calling object.

Upvotes: 0

Views: 232

Answers (2)

Federico klez Culloca
Federico klez Culloca

Reputation: 27119

Because that's how the language is defined.

As per the specs

If the form is MethodName - that is, just an Identifier - then:

  • [...] let T be the enclosing type declaration of which the method is a member, and let n be an integer such that T is the n'th lexically enclosing type declaration of the class whose declaration immediately contains the method invocation. The target reference is the n'th lexically enclosing instance of this.

Which is a long (and formal) way to say that, in your case, this is implicitly added before that method call.

Upvotes: 1

DmitryF
DmitryF

Reputation: 89

In Java all the objects have some behavior (methods). When calling a method you basically what a specific object to exercise some particular behavior.

In case the developer omits (does not specify) the object, the Java compiler assumes the method is called on the current object, i.e. "this".

The code in the question could be significantly improved to become more clean and expressive:

boolean sameAvg(GenBoundedType<?> i){
        return average() == i.average();
    }

Upd. One should also keep in mind that the comparison of floating-point numbers is a relative thing. So the method in question may produce unexpected results.

Upvotes: 1

Related Questions