-1

Is there any difference between “invoking a static method with Classname.staticMethod” and “invoking a static method with Classname::staticMethod” in java?

Also is there a difference between “invoking a method with Object.method” and “invoking a method with Object::method” in java?

Thiagarajan Ramanathan
  • 1,035
  • 5
  • 24
  • 32
  • 2
    `Classname::staticMethod` does not invoke the method, so your question is based on an incorrect assumption. `Classname::staticMethod` returns a method reference to the method. – Erwin Bolwidt Nov 21 '19 at 23:35

3 Answers3

0

Classname::staticMethod or Object::method syntax is for Consumer operations are Consumer operation representations where compiler ensures the method is accepts the given type as input type While class.method or object.method are regular method invocations :)

Maas
  • 1,317
  • 9
  • 20
0

The use of :: denotes a Method Reference and these can be used in any place where a @FunctionalInterface is required. Examples are Consumers, Functions, Predicates, Suppliers etc.... A lot of the Java 8 features. E.g. if a method requires a String which is provided through a Supplier<String>

public int methodUsingSupplier(Supplier<String> supplier) {
    String s = supplier.get();
    ...
}

and there is a method

public static String strProvider() {
    return "my String";
}

in "MyClass"

then you can:

int value = methodUsingSupplier(MyClass::strProvider);

as a way of passing the strProvider method as a 'reference' to the methodUsingSupplier method which can then utilise it.

As previously said in other answers the compiler ensures that the types and arguments match

tomgeraghty3
  • 1,234
  • 6
  • 10
0

You can use both approaches to invoke a method, and the method will behave in the same way. However you need different syntaxes for both cases. In the first approach you "directly" call the method to run its code. In the second approach you use a reference to the method and apply the methods arguments (if any) to a method defined on the reference to actually run the code. This works both for static and instance methods.

public static void staticMethodExample() {
    double d = 1.23;
    double d2 = 4.56;

    int x = Double.compare(d, d2);           // -1

    Comparator<Double> c = Double::compare;
    int y = c.compare(d, d2);                // -1
}


public static void instanceMethodExample() {
    Double d = 1.23;
    Double d2 = 4.56;

    int x = d.compareTo(d2);               // -1

    DoubleToIntFunction c = d::compareTo;
    int y = c.applyAsInt(d2);              // -1
}
Udo Borkowski
  • 311
  • 1
  • 9