Java 는 키워드 를 구현합니다 .
예시
An interface
은 관련 메서드를 "빈" 본문으로 그룹화하는 데 사용되는 추상 "클래스"입니다.
인터페이스 메소드에 액세스하려면 인터페이스가 implements
(대신에 ) 키워드 를 사용하여 다른 클래스에 의해 "구현"되어야 합니다(상속된 것과 유사 extends
). 인터페이스 메서드의 본문은 "구현" 클래스에서 제공합니다.
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
class MyMainClass {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
정의 및 사용
implements
키워드는 를 구현하는 데 사용 됩니다 interface
.
이 interface
키워드는 추상 메서드만 포함하는 특수 유형의 클래스를 선언하는 데 사용됩니다.
인터페이스 메소드에 액세스하려면 인터페이스가 implements
(대신에 ) 키워드 를 사용하여 다른 클래스에 의해 "구현"되어야 합니다(상속된 것과 유사 extends
). 인터페이스 메소드의 본문은 "구현" 클래스에 의해 제공됩니다.
인터페이스에 대한 참고 사항:
- 개체를 만드는 데 사용할 수 없습니다 (위의 예에서 MyMainClass에서 "동물" 개체를 만드는 것은 불가능합니다).
- 인터페이스 메서드에는 본문이 없습니다. 본문은 "구현" 클래스에서 제공합니다.
- 인터페이스를 구현할 때 모든 메서드를 재정의해야 합니다.
- 인터페이스 메서드는 기본적
abstract
으로public
- 인터페이스 속성은 기본적
public
으로static
,final
- 인터페이스는 생성자를 포함할 수 없습니다(객체 생성에 사용할 수 없기 때문에)
인터페이스를 사용하는 이유와 시기는?
보안을 유지하려면 특정 세부 정보를 숨기고 개체(인터페이스)의 중요한 세부 정보만 표시합니다.
Java는 "다중 상속"을 지원하지 않습니다(클래스는 하나의 수퍼클래스에서만 상속할 수 있음). 그러나 클래스가 여러 인터페이스 를 구현할 수 있기 때문에 인터페이스를 사용하여 달성할 수 있습니다 . 참고: 여러 인터페이스를 구현하려면 쉼표로 구분합니다(아래 예 참조).
다중 인터페이스
여러 인터페이스를 구현하려면 쉼표로 구분합니다.
예시
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface method
}
// DemoClass "implements" FirstInterface and SecondInterface
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}
class MyMainClass {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
관련 페이지
Java Interface Tutorial 에서 인터페이스에 대해 자세히 읽어보십시오 .