[Java 8] 16. Default & Static 메서드

seony·2023년 5월 10일

java8

목록 보기
16/16

Java8 이전 interface

  • 메서드 선언만 가능! 인터페이스 안에 메서드를 구현하는 것은 안됨!
    • 구현은 오직 구현 클래스에서만 가능했다.
  • 인터페이스를 수정하는 것은 쉽지 않은 문제가 있었다.

default 메서드 - Java8

  • 인터페이스에서 default 키워드를 사용하여 default 메서드를 구분한다.
  • 구현 클래스에서 오버라이딩을 할 수 있다.

자바 8 이전에는 Collections.sort()를 사용하여 정렬을 했겠지만 자바 8 이후에는 List 클래스에 sort를 default 메서드를 구현하여 사용할 수 있다.

static 메서드

  • default 메서드와 비슷하다.
  • 하지만 오버라이딩이 불가능하다.

List의 sort 메서드

    default void sort(Comparator<? super E> c) {
        Object[] a = this.toArray();
        Arrays.sort(a, (Comparator) c);
        ListIterator<E> i = this.listIterator();
        for (Object e : a) {
            i.next();
            i.set((E) e);
        }
    }

Default 메서드 사용 예시

package com.learn.java.defaults;

import java.util.*;

public class DefaultMethodsExample {

    public static void main(String[] args) {
        /**
         * Sort the list names in alphabetical order
          */
        List<String> stringList = Arrays.asList("Adam", "Jenny", "Alex", "Dan", "Mike", "Eric");

        /**
         * Piror java8
         */
        Collections.sort(stringList);

        System.out.println("Soreted list using Collections.sort() : "  + stringList);

        /**
         * Java 8
         */
        stringList.sort(Comparator.naturalOrder()); // Comparator를 파라미터로
        System.out.println("Soreted list using List.sort() : "  + stringList);
        stringList.sort(Comparator.reverseOrder()); // Comparator를 파라미터로
        System.out.println("Soreted list using List.sort() reverse: "  + stringList);


    }
}

Default 메서드 사용 예시2

Comparator 관련 함수

  • thenComparing을 통해서 chaining을 할 수 있다. 즉, 여러 개의 기준 값으로 정렬할 수 있다. default
  • null 값이 있어도 정렬을 할 수 있다.
    • nullsFirst() : null 값이 맨 앞으로 static
    • nullsLast() : null 값이 맨 뒤로 static
package com.learn.java.defaults;

import com.learn.java.data.Student;
import com.learn.java.data.StudentDataBase;

import java.util.Comparator;
import java.util.List;
import java.util.function.Consumer;

public class DefaultMethodsExample2 {

    static Consumer<Student> studentConsumer = System.out::println;
    static Comparator<Student> nameComparator = Comparator.comparing(Student::getName);
    static Comparator<Student> gradeComparator = Comparator.comparing(Student::getGradeLevel);

	// 이름으로 정렬
    public static void sortByName(List<Student> studentList) {
        System.out.println("After Sort " );
        studentList.sort(nameComparator); // 정렬하는 부분
        studentList.forEach(studentConsumer); // 출력하는 부분

    }
	
    // Gpa로 정렬
    public static void sortByGpa(List<Student> studentList) {
        System.out.println("After Sort " );
        Comparator<Student> gpaComparator = Comparator.comparing(Student::getGpa);
        studentList.sort(gpaComparator); // 정렬하는 부분
        studentList.forEach(studentConsumer); // 출력하는 부분

    }

	// thenComparing을 통해서 chaining
    public static void comparatorChaining(List<Student> studentList) {
        System.out.println("After comparatorChaining " );

        studentList.sort(gradeComparator.thenComparing(nameComparator));
        studentList.forEach(studentConsumer);

    }

    // null value가 있어도 정렬이 되게 하기
    public static void sortWithNullValues(List<Student> studentList) {
        // null이 맨 앞으로 오기 -> nullsFirst()
        // null이 맨 뒤로 -> nullsLast()
        Comparator<Student> studentComparator = Comparator.nullsFirst(nameComparator);
        studentList.sort(studentComparator);
        studentList.forEach(studentConsumer);
    }

    public static void main(String[] args) {
        List<Student> studentList = StudentDataBase.getAllStudents();
        System.out.println("Before sort : ");
        studentList.forEach(studentConsumer);

//        sortByName(studentList);
//        sortByGpa(studentList);
//        comparatorChaining(studentList);
        sortWithNullValues(studentList);

    }
}

Abstract Class vs Interface

  • 인터페이스에서 instance variables(인스턴스 변수)는 허용되지 않는다. 상수만 선언 가능 public static final

💡 여러 개의 인터페이스를 다중 상속 받았는데 메서드가 같다면 (메서드 충돌) 어떤 것이 상속 받아질까?

  • 해당 메서드를 구현한 클래스에서 직접 오버라이드하여 구현해야 한다.
  • 인터페이스에서 디폴트 메서드(default method)로 선언한 경우, 해당 인터페이스를 구현한 클래스에서 디폴트 메서드를 오버라이드하여 구현할 수 있다.

0개의 댓글