본문 바로가기

프로그래밍/Java

인터페이스 ( interface )

(1) 인터페이스란?

 

클래스가 상속을 통해 구현하기에 한계가 있는 경우, 즉 자바에서 불가능한 다중상속을 흉내내기 위한

도구로써 사용됩니다.(우회적 다중상속 제공)

우회적 다중상속으로 구조적 클래스 설계시 유용하게 사용됩니다.추상클래스의 경우에는 추상메서드와

일반메서드, 일반변수를 포함하고 있지만, 인터페이스는 오직 선언만 가능하기 때문에 일반메서드를

포함할 수 없습니다.(추상메서드와 상수만으로 구성)

 


(2) 인터페이스 특징

 

- 일반 클래스는 여러 인터페이스를 다중 implements(구현)하여 사용할 수 있습니다.

- 인터페이스 간의 상속에서는 다중상속이 제공됩니다.

- 인터페이스가 다른 인터페이스로부터 상속을 받았다고 하지만 오버라이딩(재정의)을 할 수는

   없습니다.(인터페이스는 body를 가지는 일반 메서드를 포함할 수 없기 때문에)

=> 상속을 받은 자식 인터페이스를 implements(구현)하는 일반 클래스에서 부모 인터페이스와

     자식 인터페이스의 추상 메서드들을 모두 재정의해야 합니다.

 


(2) 인터페이스 사용하기

- 인터페이스 기본정의

[접근제한] interface [인터페이스명] {

   상수;

   추상메서드;

}


- 인터페이스 다중상속하기

[접근제한] interface [인터페이스명] extends 부모인터페이스명1,부모인터페이스명2,

                                                                       …,부모인터페이스명n {

   상수;

   추상메서드;

}


- 인터페이스 implements(구현)하기

[public/final/abstract] class [클래스명] extends [상위클래스명]

                                                                implements [인터페이스명...n]{

   // 인터페이스에 선언된 추상메소드를 오버라이딩하여 선언

}

 

 


(3) Sample Code

 

- 인터페이스 상수 사용

 

package com.inter;

interface A1{
                                                  //상수(모두 메모리에 등재된 상태)
     int W = 10;                               //public static final int W = 10;
     static int X = 20;                       //public static final int X = 20;
     final int Y = 30;                        //public static final int Y = 30;
     public static final int Z = 40;      //원형
}

 

public class Round01 {
 public static void main(String[] args) {
          //A1 ap = new A1(); //Compile Error
          //A1.W = 100;  //Compile Error
  
  System.out.println("W = "+A1.W);
  System.out.println("X = "+A1.X);
  System.out.println("Y = "+A1.Y);
  System.out.println("Z = "+A1.Z);
 }
}


 

 

 


- 인터페이스 implements 하기

 

package com.inter;

interface A2{                  //추상메소드
             
 void aaa();                              //public abstract void aaa();
 public abstract void bbb();        //원형
}

 

interface A3{                //추상메소드
  void ccc();
}

class B2 implements A2, A3{
                                             //추상메소드 반드시 구현
 public void aaa(){
  System.out.println("aaa 메서드");
 }
 public void bbb(){
  System.out.println("bbb 메서드");
 }
 public void ccc(){
  System.out.println("ccc 메서드");
 }
}

public class Round02 {
 public static void main(String[] args) {
  B2 bp = new B2();
  bp.aaa();
  bp.bbb();
  bp.ccc();
 }
}


참조 : http://jjup77.blog.me/50110266029

 

'프로그래밍 > Java' 카테고리의 다른 글

File API  (0) 2012.06.19
다형성을 메소드 인자  (0) 2012.06.18
super 실습하기  (0) 2012.06.18
상속?  (0) 2012.06.18
Array [ 배열 ]  (0) 2012.06.12