private이 될 수 없음실행 로직을 전혀가지고 있지 않은, 그저 다형성을 위한 부모 타입으로써의 껍데기.
abstract를 정의에 쓰면 안됨parameter로 쓰일 수 있음
public static final (굳이 안적어도 됨)모든 method define 할 필요 없음
define하지 않은 method는 abstract로 표시
모든 method define 필요
모든 method가 public으로 declare되어야 함
implement하는 class도 interface에 있는 method를 define할 때 public으로 해야함.
1) (파일명 = Interface명).java 로 쓰임
2) 컴파일시 .class로 byte code가 나타남
| Feature | Class | Interface |
|---|---|---|
| Instantiation | ㅇㅇ | ㄴㄴ |
| Constructors | Contains constructors | Does not contain constructors |
| Methods | Can have both abstract and concrete methods | All methods are abstract |
| Instance variables | ㅇㅇ | ㄴㄴ (only static and final fields) |
| Inheritance | Extended by a class | Implemented by a class |
| Multiple inheritance | Cannot extend multiple classes | Can extend multiple interfaces |
interface A {
void methodA();
}
interface B {
void methodB();
}
interface C extends A, B {
void methodC();
}
base interface, derived interface의 모든 method를 구현해야 함
Comparable interfaceArrays.sort()를 사용하려면 Comparable을 implement한 objects만 가능public int compareTo(Object other)만 구현하면 됨아니라면 ClassCastException throw
| 음수 | this < other |
| 0 | this = other |
| 양수 | this < other |
java.lang => import 필요 ㄴㄴpublic class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Person other) {
return this.name.compareTo(other.name);
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
public static void main(String[] args) {
Person[] people = {
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
};
Arrays.sort(people);
for (Person person : people) {
System.out.println(person);
}
}
}