java/객체지향 프로그래밍

자바 인터페이스(interface)

appmaster 2019. 4. 16. 17:51

인터페이스란?

서로 다른 장치들이 연결되어서 상호 데이터를 주고받는 규격을 의미한다. 인터페이스는 특히 컴퓨터 주변 장치에 많다. 각자 클래스를 다른 사람의 클래스와 연결하려면 클래스 간의 상호작용을 기술하는 일종의 규격(조건)이 있어야 한다. 그래야만 클래스들이 서로 잘 접속될 것이다. 이러한 규격을 인터페이스(interface)라고 부른다.

 

인터페이스를 정의 하는것은 클래스를 정의하는 것과 유사하다. 다만 키워드 class를 사용하지 않고 interface를 사용한다.

 

interface Drawable {

    void draw();

} // Drawable 인터페이스 안에는 draw() 추상 메소드만 정의 되어 있다.

 

즉 메소드 이름과 매개변수만 존재하고, 몸체가 없으며 세미콜론으로 종료된다. 참고로 인터페이스 안의 모든 메소드는 public과 abstract을 붙이지 않아도 public과 abstract로 취급된다.

 

 

인터페이스 구현

인터페이스만으로는 객체를 생성할 수 없다. 인터페이스는 다른 클래스에 의하여 구현(implement)될 수 있다. 인터페이스를 구현한다는 말은 인터페이스에 정의된 추상 메소드의 몸체를 정의한다는 의미이다. 클래스가 인터페이스를 구현하기 위해서는 implement 키워드를 사용한다.

 

interface Drawable {

   void draw();

}

class Circle implements Drawable {    // 구현한다.

    int radius;

    public void draw() {

         System.out.println("Circle Draw");

       }

}

 

public class TestInterface1 {

       public static void main(String args[]) {

               Drawable obj = new Circle();    // Circle class에는 Drawable 객체가 들어있기 때문이다.

               obj.draw();

        }

}

 

출력 값

Circle Draw

 

 

어떤 클래스가 인터페이스를 구현하려면 인터페이스에 포함된 모든 추상 메소드를 구현하여야 한다. 클래스가 인터페이스에 있는 하나의 메소드라도 빠뜨린다면 컴파일러는 오류를 발생한다.

 

 

상속과 동시에 인터페이스를 구현할 수 있다.

 

class Shape {

    protected int x, y;

}

 

interface Drawable {

    void draw();

}

 

class Circle extends Shape implements Drawable {

     int radius;

     public void draw () {

         System.out.println("Circle Draw");

      }

}

 

public class TestInterface2 {

   public static void main(String[] args) {

       Drawable obj = new Cirlce();

       obj.draw();

    }

}

 

인터페이스로 다중 상속 구현

 

interface Printable {

    void print();

}

 

interface Drawable {

    void draw();

}

 

public class Circle implements Printable, Drawable {

      public void print() {

         System.out.println("프린터로 원을 출력합니다.")

}

 

public void draw() {

   System.out.println("화면에 원을 그립니다.");

}

 

public static void main (String args[]) {

      Circle obj = new Circle();

      obj.print();

      obj.draw();

 

    }

}

'java > 객체지향 프로그래밍' 카테고리의 다른 글

call by value  (0) 2019.07.10
자바 메소드(Method)  (0) 2019.07.10
자바 실제 객체  (0) 2019.04.16
자바 상속과 다형성  (0) 2019.04.16
자바 추상클래스  (0) 2019.04.16