Patel Parth
Patel Parth

Reputation: 315

valueof method in class Integer

We know that valueof method in Integer class is static. But when we call by an object of Integer class then it is not giving any error. ex: following code is running perfectly...

public class Test {
    public static void main(String[] args)
    {

        Integer i=new Integer(5);
        System.out.println(i.valueOf(i));
    }
}

Upvotes: 1

Views: 118

Answers (2)

millimoose
millimoose

Reputation: 39950

Quoting the Java tutorial on "Understanding Class Members":

Note: You can also refer to static methods with an object reference like instanceName.methodName(args) but this is discouraged because it does not make it clear that they are class methods.

This should be as good an official source as any.


The JLS stuff that seems to apply:

15.12.3. Compile-Time Step 3: Is the Chosen Method Appropriate?

  • The invocation mode, computed as follows:
    • If the compile-time declaration has the static modifier, then the invocation mode is static.

15.12.4.1. Compute Target Reference (If Necessary)

  • If form is ExpressionName . [TypeArguments] Identifier, then:
    • If the invocation mode is static, then there is no target reference. The ExpressionName is evaluated, but the result is then discarded.
  • If the form is Primary . [TypeArguments] Identifier involved, then:
    • If the invocation mode is static, then there is no target reference. The Primary expression is evaluated, but the result is then discarded.

So, it's allowed insofar as there are rules defined for how to evaluate that sort of expression. Which is that:

  • static methods are always called using a static invocation. (This seems obvious, but it's still something that should be specified. Say, hypothetically, Java introduces something like C# extension methods in the future, those would follow different rules.)
  • The value of the receiver expression is ignored for the purposes of the static method call. (Although it does get evaluated before the call.)

This is how such a call is evaluated at runtime. That's a a distinct step from how the compiler determines the method to call, which happens earlier. However, that part of the spec is inscrutable to me. That said it's easy to verify that the compile-time type of the receiver expression matters there, as does the fact that the method being called is static. (The static type is all the compiler has to work with, and static calls are early-bound.)

Upvotes: 5

ControlAltDel
ControlAltDel

Reputation: 35011

what's more interesting is this case:

public class A {
  public static int foo() {
    return 0;
  }
}

public class B extends A{
  public static int foo() {
    return 1;
  }
}

public static void bar() {
  A a = new B();
  System.out.println("val: " + a.foo());
}

Prints '0', because a is declared as an A

Upvotes: 0

Related Questions