한 걸음 두 걸음

자바 JAVA ] 인터페이스 interface / CompareTo, Comparable 본문

Language/Java

자바 JAVA ] 인터페이스 interface / CompareTo, Comparable

언제나 변함없이 2019. 11. 20. 17:53
반응형

인터페이스

인터페이스 개념

인터페이스란 추상클래스의 확장개념으로, 서비스 공급자(서버)와 사용자(클라이언트)간의 계약을 표현하는 것입니다.
인터페이스의 모든 필드(변수)는 모두 final static이 붙은 상수로 간주됩니다.(생략되어 표시되지 않습니다.)
메소드는 추상메소드만 구현할 수 있었으나, JAVA9부터는 구현메소드와 정적메소드, private 메소드가 작성될 수 있게 되었습니다.(private메소드는 default메소드에서 호출하여 사용할 수 있습니다.)

public interface A{
    double MAX = 10; //상수필드

    //추상메소드
    public void print();
    public void draw(int a );


    //디폴트메소드 : 구현메소드를 작성하기 위햐서는 default를 같이 작성해주어야합니다.
    public default void bb(){
        //구현코드 
    }

    //static 메소드 
    public static String cc(){
    }
}

여기서 추상메소드 반드시 자식클래스에서 구현해주어야합니다.

인터페이스 구현

인터페이스를 상속받을 때는 implements 키워드를 사용하며, 다중 상속을 지원하기 때문에 여러 개의 인터페이스를 사용할 수 있습니다. 인터페이스는 인터페이스를 상속(extends)받아 확장시키는 것도 가능합니다.

default method는

자바8부터 업데이트 되었으며, default키워드를 붙여 사용해줍니다.
기존에 있던 인터페이스를 바꾸기 위해 새롭게 메소드를 쉽게 추가할 수 있도록 만드는 디폴트 메소드를 업데이트하게 된 것입니다. 이는 추상메소드가 아니기 때문에 자식클래스에 영향을 끼치지 않습니다. 디폴트메소드는 선택적으로 오버라이드하여 사용할 수 있습니다.

정적 메소드와 기본 메소드

원래는 인터페이스 내에 붙일 수 없었으나, Java8이후부터 default 메소드와 static 메소드 추가가 가능해져서 컴패니언 클래스가 필요하지 않게 되었습니다. static메소드는 인터페이스명.static메소드명()으로 사용합니다.

Comparable인터페이스 CompareTo함수

객체의 크기를 비교하거나 정렬할 때 사용되는 것이 Comparable 인터페이스입니다. 이는 자바에서 기본적으로 제공하며, compareTo 추상메소드를 하나 갖습니다.


인터페이스 정보

public interface Comparable
This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.
Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C. Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.

It is strongly recommended (though not required) that natural orderings be consistent with equals. This is so because sorted sets (and sorted maps) without explicit comparators behave "strangely" when they are used with elements (or keys) whose natural ordering is inconsistent with equals. In particular, such a sorted set (or sorted map) violates the general contract for set (or map), which is defined in terms of the equals method.

메소드 정보

int compareTo(T o)
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)

The implementor must also ensure that the relation is transitive: (x.compareTo(y) > 0 && y.compareTo(z) > 0) implies x.compareTo(z) > 0.

Finally, the implementor must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.

It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."

In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero, or positive, respectively.

Parameters:
o - the object to be compared.
Returns:
a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Throws:
NullPointerException - if the specified object is null
ClassCastException - if the specified object's type prevents it from being compared to this object.


참고 : https://docs.oracle.com/javase/9/docs/api/java/lang/Comparable.html


인터페이스 내부

추상메소드가 하나뿐인 메소드를 함수형 메소드라하며, @FunctionalInterface 어노테이션을 붙여 사용할 수 있습니다.

public interface Comparable{
    int compareTo(Object o); //Object보다 작으면 -1 같으면 0 크면 1
}

Comparable이 구현된 클래스 간단한 예시

public class A implements Comparable{
    int num;
    public A(int n){
        num = n;
    }

    //인터페이스 재정의 메소드
    public int compareTo(Object o){
        A a = (A) o;
        if( this.num < o.num)
            return -1;
        else if( this.num == o,num)
            return 0;
        else 
            return 1;
    }
}

정렬에 사용되는 Comparale인터페이스
Arrays클래스 내부에는 sort()거 구현되어 있는데, 이는 Comparable인터페이스를 구현한 경우에만 사용할 수 있습니다.

Comparable 인터페이스가 상속된 A클래스

public class A implements Comparable{
    public int num;
    public String str;
    public A(int n, String s){
        num = n;
        str = s;
    }

    //인터페이스 재정의 메소드
    public int compareTo(Object o){
        A a = (A) o;
        if( this.num < o.num)
            return -1;
        else if( this.num == o,num)
            return 0;
        else 
            return 1;
    }
}

A클래스의 크기 비교는 num을 기준으로 됩니다.

public class Main {
    public static void main(String[] args) {
        A[] a = new A[5];
        for(int i = 0 ; i < a.length(); i++){
            a[i] = new A(i , "문자열");
        }

        Arrays.sort(a); 
        for(A as : a){
            System.out.println(as.num); //num값이 작은 순서대로 출력됩니다. 
        }
    }
}

 이렇게 보니 정말 추상클래스와 인터페이스 사이의 경계가 모호해졌네요. 추상클래스는 다중상속이 안되는데 인터페이스는 다중상속이 된다는 점이 다를 수 있겠습니다.

 

 

반응형