Java 중첩 클래스 및 Lambda 표현식

[자바 섬🤔 게시물 #2]


자바는 매우 풍부한 특성을 가지고 있으며 개발자에게 그들의 실현을 선택할 수 있는 많은 옵션을 제공한다. 그 중 두 가지는 플러그인 클래스와 lambda 표현식이다.
나는 코드 라이브러리의 어떤 부분을 읽을 때, 나는 플러그인 유형 간의 차이를 아직 완전히 이해하지 못했다는 것을 깨달았다.다음 부분은 주로 플러그인 클래스의 자바 문서를 바탕으로 하기 때문에 깊이 있는 해석here을 볼 수 있다.

카탈로그

  • Nested Classes
  • Why Use Nested Classes
  • Inner Classes
  • Static Nested Classes
  • Shadowing in Nested Classes
  • Serialization of Nested Classes
  • Local and Anonymous Classes
  • Lambda Expressions
  • Functional Interface
  • Target Typing In Lambdas
  • Method References
  • When to Use Nested Classes, Local Classes, Anonymous Classes and Lambda Expressions
  • 📌 내부 클래스

    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.

    1. Non-static nested classes are called inner classes. They have access to other members of the enclosing class, even if they are declared private.
    2. Nested classes that are declared static are called static nested classes. They DO NOT have access to other members of the enclosing class.
    3. As a member of the outer class, a nested class can be declared private , public , protected or package-private .
    4. Note that outer classes can only be declared public or package-private .

    📌 중첩 클래스를 사용하는 이유

    1. It is a way of logically grouping classes that are only used in one place.
    2. It increases encapsulation.
    3. It can lead to more readable and maintainable code.

    📌 내부 계급

    1. An inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields.
    2. As an inner class is associated with an instance, IT CANNOT DEFINE ANY STATIC MEMBERS ITSELF..
    3. 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.
    4. To instantiate an inner class, the outer class must first be instantiated.
    5. There are two special kinds of inner classes: local classes and anonymous classes.
    public class OuterClass {
        private class InnerClass {
            // class content here
        }
    }
    

    📌 정적 중첩 클래스

    1. As with class methods, a static nested class is associated with its outer class.
    2. 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.
    3. 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
        }
    }
    

    📌 중첩 클래스의 그림자

  • If a declaration of a type in a particular scope has the same name as another declaration in the enclosing scope, then the declaration shadows the declaration of the enclosing scope.
  • The shadowed declaration cannot be referenced by its name alone. Note, you can actually do this : ShadowTest.this.x . Go to shadowing section of this link .
  • 는 구성원 변수를 가리키는데 이런 변수는 그들이 속한 클래스를 통해 비교적 큰 작용역을 괄호한다.예를 들면 ff입니다.문장은 방법에서 클래스ShadowTest에 접근하는 구성원 변수입니다.
  • System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
    

    📌 계열화

  • Serialization of inner classes, including local and anonymous classes is strongly discouraged. When the Java compiler compiles certain constructs such as inner classes, it creates synthetic constructs; these are classes, methods, fields and other constructs that do not have a corresponding construct in the source code. Synthetic constructs enable Java compilers to implement new Java language features without changes to the JVM. However, they may vary among different implementations.
  • Might have compatibility issues if an inner class is serialized and then deserialize it with a different JRE implementation.
  • Read more at the Serialization section of this link
  • 📌 로컬 및 익명 클래스

    1. 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.
    2. 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
            }
        }
    }
    
  • 국부 클래스는 블록에 정의된 클래스이고 블록은 0개 이상의 문장이다.
  • 로컬 클래스는 방법체, for 순환,if 서브문장에 정의할 수 있습니다.
  • 로컬 클래스는 폐쇄 클래스의 구성원을 방문할 수 있습니다.그것은 또한 국부 변수에 접근할 수 있다.

  • 중요한 알림: 국부 클래스는final로 표시된 국부 변수에만 접근할 수 있습니다.당국 부류가 폐쇄 블록의 국부 변수나 파라미터에 접근할 때 이 변수나 파라미터를 포착합니다.
  • 자바 8에서 시작하여 하나의 국부 클래스는 폐쇄 블록의 국부 변수와 파라미터에 접근할 수 있다. 이런 변수와 파라미터는final 또는 실제final이다.변수나 파라미터의 값은 초기화된 후에 영원히 바뀌지 않으며, 실제로는 최종적이다.
  • 역시 자바SE8에서 시작하여 방법에서 로컬 클래스를 설명하면 이 방법의 매개 변수에 접근할 수 있습니다.
  • 국부류는 내부류와 유사하다. 왜냐하면 정적 구성원을 정의하거나 성명할 수 없기 때문이다.
  • 정적 방법 중의 국부 클래스는 폐쇄 클래스의 정적 구성원만 인용할 수 있다.
  • 국부류는 폐쇄 블록의 실례 구성원에 접근할 수 있기 때문에 비정적이다.따라서 대부분의 정적 성명을 포함할 수 없다.
  • 블록 내에서 인터페이스를 선언할 수 없습니다.인터페이스는 본질적으로 정적이다.
  • 로컬 클래스에서 정적 초기값 설정 항목이나 구성원 인터페이스를 설명할 수 없습니다.
  • 국부류는 정적 구성원이 있을 수 있는데 전제는 상량 변수이다.상수 변수는 원어 형식이나 문자열 형식의 변수로final로 성명되고 컴파일할 때 상수 표현식으로 초기화됩니다.컴파일할 때 상수 표현식은 일반적으로 컴파일할 때 계산할 수 있는 문자열이나 산술 표현식이다.
  • 📌 익명 클래스


        SomeAnonyMousClass anonClass = new SomeAnonyMousClass(){
            // instance field declarations
            // methods 
            // should contain no constructor
        };
    
  • 익명 클래스는 코드를 더욱 간결하게 한다.그것은 동시에 성명과 실례화류를 할 수 있다.그것들은 로컬 클래스와 유사하지만 이름이 없습니다.
  • 로컬 클래스는 클래스 성명이고 익명 클래스는 표현식이다. 이것은 이 클래스가 다른 표현식에서 정의되었다는 것을 의미한다.
  • 익명 클래스 표현식의 문법은 구조 함수의 호출과 유사하며 코드 블록에 클래스 정의만 포함한다.
  • HelloWorld helloWorld = new HelloWorld() {
      // code here
    };
    
  • 익명 클래스 표현식은 다음과 같은 내용으로 구성된다. new 연산자, 실현할 인터페이스나 확장할 클래스의 이름, 구조 함수 파라미터를 포함하는 괄호, 일반 클래스 실례로 표현식을 만들고 클래스 성명체로 하는 괄호와 같다.
  • 익명 클래스의 정의는 표현식이기 때문에 문장의 일부분이어야 한다.이것은 왜 오른쪽 괄호 뒤에 분호가 있는지 설명한다.
  • 📌 폐쇄된 범위의 국부 변수에 접근하고 익명 클래스의 구성원을 성명하고 접근합니다

  • 로컬 클래스와 마찬가지로 익명 클래스는 변수를 포획할 수 있다.그것들은 폐쇄된 범위 내의 국부 변수에 대해 같은 접근 권한을 가지고 있다.
  • 익명 클래스는 폐쇄 클래스의 구성원을 방문할 수 있다.
  • 익명 클래스는 폐쇄된 범위 내에서final 또는 유효final로 명시되지 않은 국부 변수에 접근할 수 없습니다.
  • 플러그인 클래스와 마찬가지로 익명 클래스의 형식 성명은 폐쇄 범위에서 같은 이름을 가진 다른 성명을 숨깁니다.
  • 익명 클래스는 구성원에게도 로컬 클래스와 같은 제한이 있다. 정적 초기값 설정 항목이나 구성원 인터페이스를 설명할 수 없다.익명 클래스에는 정적 구성원이 있을 수 있으며, 전제는 상수 변수이다.
  • 주의,ff는 익명 클래스에서 성명할 수 있습니다

    b. 추가 방법
    c. 실례 초기값 설정 항목
    d, 현지반
  • 중요한 알림: 익명 클래스에서 구조 함수를 설명할 수 없습니다.
  • 익명 클래스는 두 가지 또는 여러 가지 방법을 포함하는 인터페이스를 실현하기에 매우 적합하다.
  • 상술한 차원 구조를 총괄하기 위해 아래 그림은 삽입류의 유형을 나타낸다.

    📌 표현식

    1. Lambda Expressions enables developers to treat functionality as a method argument, or code as a data.
    2. 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로 구성되어 있습니다.
  • 쉼표로 구분된 형식의 매개 변수 목록을 괄호로 묶는다.lambda 표현식에서 매개 변수의 데이터 형식을 생략할 수 있습니다.또한 매개변수가 하나인 경우 괄호를 생략할 수 있습니다.
  • 화살표 ->
  • 단일 표현식 또는 문 블록으로 구성된 바디입니다.return 문장도 사용할 수 있지만, return 문장은 lambdas의 표현식이 아니기 때문에 괄호로 묶어야 한다는 것을 기억하십시오.lambda는 이름 없는 방법으로 볼 수 있다.
    예를 들어,
  • 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는 변수를 포획할 수 있다.그것들은 폐쇄된 범위 내의 국부 변수에 대해 같은 접근 권한을 가지고 있다.그러나 로컬 클래스와 익명 클래스와 달리 lambda는 음영 문제가 없습니다.
  • lambda는 어휘 범위입니다.이것은 초유형에서 어떤 명칭도 계승하지 않고 새로운 단계의 작용역도 도입하지 않는다는 것을 의미한다.lambda의 성명은 폐쇄된 환경의 성명과 같이 해석됩니다.
  • lambda에 전달된 매개 변수가 폐쇄된 범위 내에서 설명하면 컴파일러가 오류를 생성합니다 Lambda expression's parameter {} cannot redeclare another local variable defined in an enclosing scope.이것은 lambda 표현식이 새로운 단계의 작용역을 도입하지 않았기 때문이다.따라서 lambdas는 폐쇄 범위의 필드, 방법, 국부 변수에 직접 접근할 수 있습니다.
  • 국부 클래스와 익명 클래스와 마찬가지로 lambda 표현식은 폐쇄 블록의 최종 또는 유효한 최종 국부 변수와 파라미터만 접근할 수 있다(초기화 후 값을 변경하지 말아야 한다).
  • 📌 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 컴파일러가 대상 유형을 결정할 수 있는 경우에만 사용할 수 있습니다. 즉,
  • 변수 선언
  • 작업
  • 반환문
  • 수조 초기값 설정항
  • 방법 또는 구조 함수 매개 변수
  • lambda표현체
  • 조건 표현식
  • 배우 표정

  • 📌 대상 유형 및 메소드 매개변수
    메소드 매개변수의 경우 Java 컴파일러는 다른 두 언어 기능을 사용하여 구문 분석 및 유형 매개변수 인터페이스를 다시 로드하여 대상 유형을 결정합니다.
    예를 들어 함수 인터페이스java.lang.Runnablejava.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

    좋은 웹페이지 즐겨찾기