Java에서 Comparable 확장

Haider Ali 2023년10월12일
Java에서 Comparable 확장

이 가이드에서는 Java의 Extends Comparable Interface에 대해 학습합니다. Comparable<T>로 표시됩니다. Java의 많은 클래스에서 구현되는 인터페이스입니다. 그 측면에 대해 자세히 알아보겠습니다.

Java에서 확장 Comparable<T> 인터페이스 구현

이 인터페이스에는 compareTo(Object o)라는 하나의 메서드만 있습니다. 이 메서드는 개체를 주문에 대해 지정된 개체와 비교합니다.

객체가 지정된 것보다 작으면 음의 정수를 반환합니다. 객체와 지정된 객체가 같으면 0을 반환합니다.

마찬가지로 개체가 지정된 개체보다 크면 양의 정수를 반환합니다.

클래스는 Java에서 Java 인터페이스를 확장할 수 없습니다.

인터페이스는 인터페이스만 확장할 수 있습니다. Java 클래스는 Java 클래스만 확장할 수 있습니다.

Comparable<T>는 Java의 인터페이스이므로 Comparable 인터페이스를 확장하는 사용자 정의 인터페이스를 만들어야 합니다. 사용자 정의 클래스는 사용자 정의 인터페이스를 구현합니다.

public class Main {
  public static void main(String[] args) {
    Student s1 = new Student("Bill Gates");
    Student s2 = new Student("James");

    int res = s1.compareTo(s2);
    // comaprison of name of two students using iherited and extended method of
    // compareable.

    System.out.println(res);
  }
}
interface CustomComparable extends Comparable<Student> {
  // Custom interface which extends Comparable.
  // So CustomComparable have inherited method Compareto(Object o)
  public String getName();
}
class Student implements CustomComparable {
  // calss student implements CustomCompareable
  private String name; // String variable
  Student(String s) {
    this.name = s;
  }

  public int compareTo(Student other) { // overiding super method........... .
    return this.name.compareTo(other.getName());
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

출력:

-8

실제 Comparable<T>를 확장하여 사용자 지정 비교기 클래스를 구현하는 두 개의 학생 클래스 개체를 생성하기만 하면 됩니다. 그래서 여기에서 compareTo() 메소드를 사용할 수 있습니다.

작가: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

관련 문장 - Java Interface