자바에서 추상화를 이루기 위한 방법 중 하나로 인터페이스를 사용한다.
인터페이스는 완전한 "추상 클래스" 이다. 관계가 있는 메소드들을 그룹짓기 위해 사용한다.
인터페이스의 메소드는 선언만 있고 구현은 하지 않는다.
Example
// 인터페이스
interface Animal {
public void animalSound(); // 인터페이스 메소드 (선언만 있다.)
public void run(); // 인터페이스 메소드 (선언만 있다.)
}
인터페이스 메소드에 접근하기 위해, 인터페이스는 다른 클 클래스에 implments 키워드로 "구현" 되어야만 한다. 인터페이스 메소드의 구현은 "구현된" 클래스에 의해 제공된다:
Exmaple
// 인터페이스
interface Animal {
public void animalSound(); // 인터페이스 메소드 (선언만 있다.)
public void sleep(); // 인터페이스 메소드 (선언만 있다.)
}
// Pig는 Aniaml 인터페이스의 구현체이다.
class Pig implements Animal {
public void animalSound() {
// animalSound()의 구현은 여기서 제공된다.
System.out.println("The pig says: wee wee");
}
public void sleep() {
// sleep()의 구현은 여기서 제공된다.
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Pig 객체를 생성한다.
myPig.animalSound();
myPig.sleep();
}
}
인터페이스 참고사항
- 추상 클래스와 같이, 인터페이스는 객체를 만드는 일에 사용할 수 없다 (위 예처럼, MyMainClass에서 "Animal" 객체를 만들 수 없다.).
- 인터페이스 메소드는 본문을 가지지 않는다 - 본문은 "구현된" 클래스에 의해 제공된다.
- 인터페이스의 구현체는 반드시 인터페이스의 모든 메소드를 오버라이드 해야한다.
- 인터페이스 메소드는 기본적으로 abstract이며 public 이다.
- 인터페이스 애트리뷰트는 기본적으로 public, static, final 이다.
- 인터페이스는 생성자를 담을 수 없다. (객체를 생성할 수 없는 것 처럼)
인터페이스를 왜, 언제 쓸까?
- 보안을 확보하기 위해 - 특정한 디테일은 숨기고, 오직 객체를 사용하는데 중요한 부분만 보여주고 싶어서 사용한다.
- 자바는 "다중 상속"을 지원하지 않는다 (클래스는 오직 하나의 부모클래스만 상속받을 수 있다). 하지만, 인터페이스를 통해 "다중 구현"은 가능하다. 클래스는 여러개의 인터페이스를 구현할 수 있다.
다중 인터페이스
여러개의 인터페이스를 구현하기 위해, 컴마로 구분한다.
Example
interface FirstInterface {
public void myMethod(); // 인터페이스 메소드
}
interface SecondInterface {
public void myOtherMethod(); // 인터페이스 메소드
}
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
댓글