자바 튜토리얼

자바 홈 자바 소개 자바 시작하기 자바 구문 자바 주석 자바 변수 자바 데이터 유형 자바 타입 캐스팅 자바 연산자 자바 문자열 자바 수학 자바 부울 자바 If...Else 자바 스위치 자바 while 루프 자바 For 루프 자바 중단/계속 자바 배열

자바 메소드

자바 메소드 자바 메소드 매개변수 자바 메소드 오버로딩 자바 범위 자바 재귀

자바 클래스

자바 OOP 자바 클래스/객체 자바 클래스 속성 자바 클래스 메소드 자바 생성자 자바 수정자 자바 캡슐화 자바 패키지 / API 자바 상속 자바 다형성 자바 내부 클래스 자바 추상화 자바 인터페이스 자바 열거형 자바 사용자 입력 자바 날짜 자바 배열 목록 자바 링크드리스트 자바 해시맵 자바 해시셋 자바 반복자 자바 래퍼 클래스 자바 예외 자바 정규식 자바 스레드 자바 람다

자바 파일 처리

자바 파일 자바 파일 생성/쓰기 자바 읽기 파일 자바 삭제 파일

자바 방법

두 개의 숫자 더하기

자바 참조

자바 키워드 자바 문자열 메소드 자바 수학 메소드

자바 예제

자바 예제 자바 컴파일러 자바 연습 자바 퀴즈 자바 인증서


자바 인터페이스


인터페이스

Java에서 추상화 를 달성하는 또 다른 방법 은 인터페이스를 사용하는 것입니다.

An 은 관련 메서드를 빈 본문으로 그룹화하는 데 사용되는 interface완전히 " 추상 클래스 "입니다.

예시

// interface
interface Animal {
  public void animalSound(); // interface method (does not have a body)
  public void run(); // interface method (does not have a body)
}

인터페이스 메소드에 액세스하려면 인터페이스가 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 Main {
  public static void main(String[] args) {
    Pig myPig = new Pig();  // Create a Pig object
    myPig.animalSound();
    myPig.sleep();
  }
}

인터페이스에 대한 참고 사항:

  • 추상 클래스 와 마찬가지로 인터페이스 를 사용하여 개체를 만들 수 없습니다 (위의 예에서 MyMainClass에서 "동물" 개체를 만드는 것은 불가능함).
  • 인터페이스 메서드에는 본문이 없습니다. 본문은 "구현" 클래스에서 제공합니다.
  • 인터페이스를 구현할 때 모든 메서드를 재정의해야 합니다.
  • 인터페이스 메서드는 기본적 abstract으로 public
  • 인터페이스 속성은 기본적 public으로 static,final
  • 인터페이스는 생성자를 포함할 수 없습니다(객체 생성에 사용할 수 없기 때문에)

인터페이스를 사용하는 이유와 시기는?

1) 보안을 달성하기 위해 - 특정 세부 사항을 숨기고 개체(인터페이스)의 중요한 세부 사항만 표시합니다.

2) Java는 "다중 상속"을 지원하지 않습니다(클래스는 하나의 수퍼클래스에서만 상속할 수 있음). 그러나 클래스가 여러 인터페이스 를 구현할 수 있기 때문에 인터페이스를 사용하여 달성할 수 있습니다 . 참고: 여러 인터페이스를 구현하려면 쉼표로 구분합니다(아래 예 참조).


다중 인터페이스

여러 인터페이스를 구현하려면 쉼표로 구분합니다.

예시

interface FirstInterface {
  public void myMethod(); // interface method
}

interface SecondInterface {
  public void myOtherMethod(); // interface method
}

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();
  }
}