29
loading...
This website collects cookies to deliver better user experience
private
, public
, protected
or package-private
.public
or package-private
.public class OuterClass {
private class InnerClass {
// class content here
}
}
public class OuterClass {
static class StaticNestedClass {
// class contents here
}
}
ShadowTest.this.x
. Go to shadowing section of this link.ShadowTest
from the method.
System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
private
, public
, package-private
protected
can be used in an inner class just like how they are used for the instance fields of the outer class.public class SomeClass {
public void someMethod() {
class SomeLocalClass {
// class contents here
}
}
}
SomeAnonyMousClass anonClass = new SomeAnonyMousClass(){
// instance field declarations
// methods
// should contain no constructor
};
HelloWorld helloWorld = new HelloWorld() {
// code here
};
new
operator, the name of an interface to implement or a class to extend, parentheses that contain the arguments to a constructor, just like a normal class instance creation expression and a body, which is a class declaration body.->
p -> p.getAge() >= 18
&& p.getAge() <= 25
java.util.function
.Lambda expression's parameter {} cannot redeclare another local variable defined in an enclosing scope
. This is because lambda expressions do not introduce a new level of scoping. Consequently, lambdas can directly access fields, methods and local variables of the enclosing scope. So how can the type of a lambda expression be determined, e.g. the type of p in the example below?
p -> p.getAge() < 18
java.lang.Runnable
and java.util.Callable<V>
are implemented and overloaded by a certain class like this,void invoke(Runnable r) {
r.run();
}
<T> T invoke(Callable<T> c) {
return c.call();
}
String s = invoke(() -> "done");
Callable<V>
will be invoked because the lambda returns a value, in this case the string done
. Note that the method invoke(Runnable)
does not return a value.Arrays.sort(personListAsArray, Person::compareByAge);
Person::compareByAge
is semantically the same as the lambda expression where compareByAge
is a static method of the Person class.(person1, person2) -> Person.compareByAge(person1, person1)
Kind | Syntax | Example |
---|---|---|
Reference to a static method | ContainingClass::staticMethodName |
Person::compareByAge |
Reference to an instance method of a particular object | containingObject::instanceMethodName |
person1::compareByName |
Reference to an instance method of an arbitrary object of a particular type | ContainingType::methodName |
String::concat |
Reference to a constructor | ClassName::new |
HashSet::new |
Lambda Expressions .
Nested Class . Used for reasons similar to those of local classes, i.e. it is necessary to make the type more widely available, and access to local variables or method parameters are not needed.