극단적으로 동일한 목적 하에 동일한 기능을 수행하게끔 강제하는 것
인터페이스의 사용 이유
1. 협업
2. 교체 용이 -> 유지 보수가 편함.
3. 다중 상속
interface 인터페이스명 {
메소드(매개변수 ...)
}
class 클래스명 implements 인터페이스명 {
매소드(매개변수 ...)
}
형식으로 사용한다.
Interface Calculable {
int sum(int v1, int v2);
}
class Cal implements CAlculable {
public int sum(int v1, int v2) {
return v1 + v2;
}
}
public class Main() {
public static void main(String[] args) {
Cal c = new Cal();
System.out.println(c.sum(2, 1));
}
}
※ 하나의 클래스는 여러 개의 인터페이스를 구현할 수 있다.
인터페이스는 다중 상속이 가능하다.
interface test1 {
}
public interface test2 {
}
public interface test3 extends test1, test2 {
}
public class test implements test3 {
test1, 2, 3의 모든 기능구현;
}
다형성을 사용하는 이유는 기능들을 제한 할 수 있기 때문에 사용한다.
interface me {}
interface brother {}
interface guardian {}
class Jimin implements me {
public void me() {}
}
class Jiho implements brother, guardian {
public void brother() {}
}
이런 식으로 Jimin이라는 클래스는 me라는 인터페이스만 갖고 Jiho라는 클래스는 borther, guardian이라는 인터페이스를 가져 기능을 제한 할 수 있다.
사용 방법
default 반환자료형 메소드이름() {}
사용하는 이유
사용 방법
static 반환자료형 메소드이름() {}
객체의 생성 없이 호출 가능