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.
-
But, dear sir, does it or does it not though?Alexander– Alexander2013年12月13日 09:36:33 +00:00Commented Dec 13, 2013 at 9:36
-
1Short answer, yes. In Java 8.Boris the Spider– Boris the Spider2013年12月13日 09:36:35 +00:00Commented Dec 13, 2013 at 9:36
-
"In Java 8". So right now, no it doesn't.Gimby– Gimby2013年12月13日 09:38:35 +00:00Commented Dec 13, 2013 at 9:38
-
Why are you asking this? It seems like a strange thing to ask; I've seen "what is this operator" questions and "what operator do I use" questions, but not "does any operator look like this".user2357112– user23571122013年12月13日 09:38:36 +00:00Commented Dec 13, 2013 at 9:38
-
1stackoverflow.com/questions/20001427/…user2357112– user23571122013年12月13日 09:39:45 +00:00Commented Dec 13, 2013 at 9:39
4 Answers 4
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.
Comments
until and including Java 7: No!
Java 8: Yes!
simply as that.
Comments
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.
2 Comments
YourClass.doSomething() for that.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