Java 중첩 클래스 및 Lambda 표현식
[자바 섬🤔 게시물 #2]
자바는 매우 풍부한 특성을 가지고 있으며 개발자에게 그들의 실현을 선택할 수 있는 많은 옵션을 제공한다. 그 중 두 가지는 플러그인 클래스와 lambda 표현식이다.
나는 코드 라이브러리의 어떤 부분을 읽을 때, 나는 플러그인 유형 간의 차이를 아직 완전히 이해하지 못했다는 것을 깨달았다.다음 부분은 주로 플러그인 클래스의 자바 문서를 바탕으로 하기 때문에 깊이 있는 해석here을 볼 수 있다.
카탈로그
📌 내부 클래스
A nested class is a class within another class, i.e. a member of its enclosing class. It is divided into two categories: non-static and static.
- Non-static nested classes are called inner classes. They have access to other members of the enclosing class, even if they are declared private.
- Nested classes that are declared static are called static nested classes. They DO NOT have access to other members of the enclosing class.
- As a member of the outer class, a nested class can be declared
private
,public
,protected
orpackage-private
. - Note that outer classes can only be declared
public
orpackage-private
.
📌 중첩 클래스를 사용하는 이유
- It is a way of logically grouping classes that are only used in one place.
- It increases encapsulation.
- It can lead to more readable and maintainable code.
📌 내부 계급
- An inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields.
- As an inner class is associated with an instance, IT CANNOT DEFINE ANY STATIC MEMBERS ITSELF..
- Objects that are instances of an inner class exist within an instance of the outer class. Thus an instance of an inner class can only exist within an instance of the outer class and has direct access to the methods and fields of the enclosing instance.
- To instantiate an inner class, the outer class must first be instantiated.
- There are two special kinds of inner classes: local classes and anonymous classes.
public class OuterClass {
private class InnerClass {
// class content here
}
}
📌 정적 중첩 클래스
- As with class methods, a static nested class is associated with its outer class.
- A static nested class cannot refer directly to instance variables or methods defined in its enclosing class. It can use them only through an object reference.
- A static nested class interacts with the instance members of its outer class and other classes just like any other top level class. Thus a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
public class OuterClass {
static class StaticNestedClass {
// class contents here
}
}
📌 중첩 클래스의 그림자
ShadowTest.this.x
. Go to shadowing section of this link . ShadowTest
에 접근하는 구성원 변수입니다.System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
📌 계열화
📌 로컬 및 익명 클래스
- There are two types of inner classes : local and anonymous. An inner class within the body of a method is called a local class. An inner class can also be declared inside the body of a method without naming them, i.e. an anonymous class.
- The same modifiers used for other members of the outer class can be used for an inner class. For instance the access modifiers
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
}
}
}
중요한 알림: 국부 클래스는final로 표시된 국부 변수에만 접근할 수 있습니다.당국 부류가 폐쇄 블록의 국부 변수나 파라미터에 접근할 때 이 변수나 파라미터를 포착합니다.
📌 익명 클래스
SomeAnonyMousClass anonClass = new SomeAnonyMousClass(){
// instance field declarations
// methods
// should contain no constructor
};
HelloWorld helloWorld = new HelloWorld() {
// code here
};
new
연산자, 실현할 인터페이스나 확장할 클래스의 이름, 구조 함수 파라미터를 포함하는 괄호, 일반 클래스 실례로 표현식을 만들고 클래스 성명체로 하는 괄호와 같다.📌 폐쇄된 범위의 국부 변수에 접근하고 익명 클래스의 구성원을 성명하고 접근합니다
밭
b. 추가 방법
c. 실례 초기값 설정 항목
d, 현지반
📌 표현식
- Lambda Expressions enables developers to treat functionality as a method argument, or code as a data.
- For classes with only one method, an anonymous class, much more a named class is a bit excessive and cumbersome. Lambdas express instances of single-method classes more compactly.
📌 Lambda 표현식 구문
lambda 표현식은 ff로 구성되어 있습니다.
->
예를 들어,
p -> p.getAge() >= 18
&& p.getAge() <= 25
📌 기능 인터페이스
A functional interface is any interface that contains only one abstract method. It may contain one or more default methods or static methods. Because it only contains one abstract method, the name can be omitted when implementing it. By doing this instead of using an anonymous class expression, a lambda expression is used. The JDK defines several standard functional interfaces which can be found in the package java.util.function
.
📌 Lambda 표현식에서 닫힌 범위의 로컬 변수에 액세스하기
Lambda expression's parameter {} cannot redeclare another local variable defined in an enclosing scope
.이것은 lambda 표현식이 새로운 단계의 작용역을 도입하지 않았기 때문이다.따라서 lambdas는 폐쇄 범위의 필드, 방법, 국부 변수에 직접 접근할 수 있습니다.📌 Lambdas의 대상 유형
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
자바가 실행될 때 lambda를 전달하는 방법을 호출할 때 특정한 데이터 형식이 필요하기 때문에 lambda 표현식이 바로 이런 형식입니다.이러한 방법이 기대하는 데이터 유형을 목표 유형이라고 부른다.자바 컴파일러는 lambda 표현식의 형식을 확인하기 위해 lambda 표현식의 상하문이나 상황을 찾는 목표 형식을 사용합니다.따라서 lambda 표현식은 Java 컴파일러가 대상 유형을 결정할 수 있는 경우에만 사용할 수 있습니다. 즉,📌 대상 유형 및 메소드 매개변수
메소드 매개변수의 경우 Java 컴파일러는 다른 두 언어 기능을 사용하여 구문 분석 및 유형 매개변수 인터페이스를 다시 로드하여 대상 유형을 결정합니다.
예를 들어 함수 인터페이스
java.lang.Runnable
와 java.util.Callable<V>
가 이런 특정 클래스에 의해 실현되고 재부팅된다면void invoke(Runnable r) {
r.run();
}
<T> T invoke(Callable<T> c) {
return c.call();
}
다음 문장은 어떤 방법을 사용합니까?String s = invoke(() -> "done");
lambda가 값을 되돌려 주기 때문에, 이 예는 문자열 Callable<V>
을 가진 인자 done
를 호출합니다.메서드invoke(Runnable)
는 값을 반환하지 않습니다.📌 Lambdas의 계열화
만약 lambda의 목표 유형과 포획된 매개 변수를 서열화할 수 있다면, lambda를 서열화할 수 있습니다.그러나 내부 계급처럼🛑 lambda의 서열화를 강력히 반대하다.
📌 방법 인용
Lambdas can be used to create anonymous methods. However, there are times when it does nothing but call an existing method. In these cases, it is often clearer to refer to the existing method by name, called method referencing. They are compact, easy-to-read lambdas for methods that already have a name.
For instance this can be done in sorting an array of Person objects by age.
Arrays.sort(personListAsArray, Person::compareByAge);
The method reference 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)
방법 인용의 종류
방법 인용에는 네 가지 유형이 있다
선량했어
구문
예.
정적 방법에 대한 인용
ContainingClass::staticMethodName
Person::compareByAge
특정 대상의 실례 방법에 대한 인용containingObject::instanceMethodName
person1::compareByName
특정 유형의 임의의 대상에 대한 실례 방법의 인용ContainingType::methodName
String::concat
구조 함수에 대한 인용ClassName::new
HashSet::new
📌 중첩 클래스, 로컬 클래스, 익명 클래스 및 Lambda 표현식을 사용하는 경우
Nested Classes enable the logical grouping of classes that are only used in one place, increase the use of encapsulation, create more readable and maintainable code. Local classes, anonymous classes and lambda expressions also share the same advantages but they are usually used for more specific situations:
- Local Class . Used if creating more than one instance of a class is needed, access its constructor and/or introduce a new, named type.
- Anonymous Class . Used if declared fields or additional methods are needed
-
Lambda Expressions .
- Used for encapsulating a single unit of behavior that is passed to the other parts of the code.
- Used if a simple instance of a functional interface is needed and some other criteria like constructor, named type, fields or additional methods are not needed
-
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.
- Inner class should be used if access to an enclosing instance's non-public fields and methods are required.
- Static class should be used if there is no instance field that needs to be accessed from the class.
Getting used and familiar with nested classes and advanced lambdas with generics certainly takes a lot of reading code and practice. We will eventually get there.
As always, cheers to continued growth and learning 🍷!
추천자
[1] Java Nested Classes
[2] Nested Classes in Java
Reference
이 문제에 관하여(Java 중첩 클래스 및 Lambda 표현식), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/pat_the99/java-nested-classes-and-lambda-expressions-18o6텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)