-2

In cases where it does not seem to matter, i.e. the value is a parameter and the function is not operating directly on the calling object instance, what are the "under the hood" differences between calling a Class.function() and Object.function()?

This can be illustrated by a convoluted example:

Character c = new Character();
boolean b = c.isDigit(c);

vs.

boolean b = Character.isDigit(c);

I can see cases where hardcoded variables would easier to change (find/replace) if only Character were used repeatedly instead of a bunch of different instance names. MOST IMPORTANTLY: What is the accepted best practice?

5
  • 2
    isDigit is a static method and should only be used as such. Commented Oct 20, 2016 at 11:47
  • 2
    Static members belong to the class and not to the object. However, Java designers have allowed us to call static methods from an object of the class instead of the class itself, because there is no real ambiguity. Perhaps a design flaw. Commented Oct 20, 2016 at 11:47
  • I can see the similarities between this question and the one suggested as a duplicate. However, this question builds on that answer by asking what the best practice is. There are always differences, even if only in coding style. Commented Oct 20, 2016 at 11:55
  • "Apple extends Banana". That's a first. Commented Oct 20, 2016 at 11:59
  • More like "Granny Smith" extends "Apple" Commented Oct 20, 2016 at 12:02

2 Answers 2

0

for static methods, internally c.isDigit(c) is treated as Character.isDigit(c);

Compiler simply replaces reference variable with Class name in case of static methods called using reference variables.

Sign up to request clarification or add additional context in comments.

3 Comments

...and if the method is not defined as static?
then they must be called on instance. You cannot call non static methods using class name.
@user58446: If the method isn't static, you can't call it via the class name.
0

There's no difference at all. It's a quirk of Java syntax that you're allowed to call static methods via an instance reference. The compiler emits the same bytecode regardless of whether you call Character.isDigit or c.isDigit, and doesn't even care if c is null at runtime (because c isn't involved in the call at runtime — because the bytecode is doing Character.isDigit).

4 Comments

"and doesn't even care if c is null at runtime`." - that is cool.
@Gendarme No, it's awful. But there's nothing we can do about it now.
Does it work even if c is declared to be null during compile time?
@Gendarme: It doesn't even care if it's a compile-time constant, no: System.out.println(((Character)null).isDigit('2')); works just fine. ideone.com/hcw23U Because again, no instance is used. All the compiler uses the instance reference for is type information.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.