Does Java have a ::
operator? Please, do not close this question, I did search the docs and I'm sure it does not but I want to be completely sure.
I.e can there be something like MyClass::x
or anything visually resembling that in Java.
Does Java have a ::
operator? Please, do not close this question, I did search the docs and I'm sure it does not but I want to be completely sure.
I.e can there be something like MyClass::x
or anything visually resembling that in Java.
In Java 8 the operator ::
has been introduced as a way to refer to a method. Basically, it turns the method into a first-class object, something you can pass to other methods as an argument, store in a variable, and return from a method.
This addition to the syntax is a part of the overall orientation towards the Functional Programming paradigm which is being introduced with Java 8. The elementary feature of FP are higher-order functions—such functions which accept other functions as argument, or return functions. This paradigm allows one to eliminate much boilerplate which now pervades the Java source code.
In Java 8 it allows for referencing of static members of a class, similar to PHP.
public class YourClass {
public static int comparer(String one, String two){
return one.length() - two.length();
}
public static void main(String[] args) {
Arrays.sort(args, YourClass::comparer);
//args are now sorted
}
}
As stated in comments, this is Java 8 (and later) only. JDK 7 and below does not have this.
Upto Java 7 there is no double colon operator(::) in java as in C++. But Java 8 introduce double colon operator which is used to refer the methods.
Example(For Static Method)
public class TestClass {
public void functionTest() {...}
}
We can call function 'functionTest()' by using double colon operator(::).
TestClass t=new TestClass();
t::functionTest
If 'functionTest()' is static then we can refer directly by using class name
TestClass::functionTest
There are four kinds of method references(as written in java doc)
For more information refer java doc