프로그래밍 언어/자바(JAVA)

자바(JAVA) - 익명 클래스 (Anonymous class)

나아가는중 2022. 1. 21. 17:37
반응형

익명 클래스란 이름이 없는 일회용 클래스입니다. 일회용으로만 사용하기 때문에 이름이 필요 없으며 객체 생성 시에 클래스 정의와 생성을 동시에 합니다. 

 

보통의 자바 클래스는 클래스를 정의하고 클래스명으로 객체를 생성합니다.

// 클래스 정의
class MyClass {
    ...
}

// 객체 생성
MyClass myClass = new MyClass();

 

 

객체를 생성해주는 new 연산자 뒤에 부모 클래스(인터페이스)의 이름을 사용하여 생성하며, {} 안에 함수를 정의합니다.

하나의 부모 클래스를 상속받거나 단 하나의 인터페이스만을 구현할 수 있습니다.

// 생성과 정의를 동시에
Object myClass = new Object() {
    void myMethod() {
        ...
    }
};

 

 

학생 클래스의 배열을 나이순으로 정렬하는 예제입니다.

여기에서 사용된 MyComparable 클래스는 정렬시에 한 번만 사용되는 일회용 클래스이므로 익명 클래스로 만들어 사용할 수 있습니다.

 

import java.util.Arrays;
import java.util.Comparator;

public class AnonymousClass {
    public static void main(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student(17, 'M');
        students[1] = new Student(18, 'F');
        students[2] = new Student(20, 'M');

        Arrays.sort(students, new MyComparable());

        for (Student student : students) {
            System.out.println(student.age); // 출력 결과 : 17, 18, 20
        }
    }
}

class Student {
    int age;
    char sex;

    public Student(int age, char sex) {
        this.age = age;
        this.sex = sex;
    }
}

class MyComparable implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.age - o2.age;
    }
}

 

MyComparable 클래스를 익명 클래스로 바꾼 예제입니다.

import java.util.Arrays;
import java.util.Comparator;

public class AnonymousClass {
    public static void main(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student(17, 'M');
        students[1] = new Student(18, 'F');
        students[2] = new Student(20, 'M');

        // 익명 객체 생성 
        Comparator<Student> MyComparator = new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.age - o2.age;
            }
        };
        
        Arrays.sort(students, MyComparator);

        for (Student student : students) {
            System.out.println(student.age);
        }
    }
}

class Student {
    int age;
    char sex;

    public Student(int age, char sex) {
        this.age = age;
        this.sex = sex;
    }
}
import java.util.Arrays;
import java.util.Comparator;

public class AnonymousClass {
    public static void main(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student(17, 'M');
        students[1] = new Student(18, 'F');
        students[2] = new Student(20, 'M');

        // 익명 객체 생성 
        Arrays.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.age - o2.age;
            }
        });

        for (Student student : students) {
            System.out.println(student.age);
        }
    }
}

class Student {
    int age;
    char sex;

    public Student(int age, char sex) {
        this.age = age;
        this.sex = sex;
    }
}

 

 

컴파일 시에는 익명클래스는 외부클래스명$숫자.class 형식으로 파일이 생성됩니다.

파일 형식이 내부클래스와 유사하나 이름이 없는 클래스이므로 숫자 뒤에 이름이 없습니다.

FileName.class
// 익명 클래스
FileName$1.class
FileName$2.class

 

반응형