Web develop/JAVA

[JAVA] 자바 인터페이스 형식, 사용 예시

ForA 2019. 4. 23. 18:15
728x90
  • 연결자를 뜻함. 인터페이스에 선언한 클래스는 반드시 정의되어 있어야 한다.

  • 메뉴판 -> 인터페이스

형식)
interface 인터페이스명
{
//필드
public static final int su = 0;
//static -> 정적 메모리할당, new -> 동적 메모리할당

//선언된 메소드
public abstract void print();

}
  • interface의 구성멤버는 필드, 선언된 메소드로만 구성된다.

    void print() { } →정의된 메소드, 구현된 메소드
    void print(); →선언된 메소드(바디없는, 영역괄호 없는 메소드)

  • 선언된 메소드의 접근제한자 명시는 public만 할 수 있다. 다른 접근제한자는 불가능

  • public과 abstract는 생략가능하다

  • 생성한 인터페이스는 클래스에 구현해서 사용

  • 키워드: imprements

class 클래스명 implements 인터페이스명{

    @Override
    public void 메소드명 {

    }
  }

 

클래스와 인터페이스 간의 상속문법 사용 예시

class A{}

class B extends A{ //extends 뒤에는 상속 받고자 하는 한 개의 클래스명만 정의
                   //extends 확장(자식클래스를 확장클래스)
}

interface A{}  
interface B{}

class C implements A,B { //A와 B 인터페이스 내의 선언된 메소드를 C클래스에서 전부 구현

  //구현의 약속

}

interface A {}  
class B {}

class C implements A extends B {  
//에러발생 : 클래스와 인터페이스를 동시에 상속할 때는 클래스 먼저, 인터페이스는 나중에  
// implements가 먼저 나오면 컴파일러가 extends Object를 implements 키워드 앞에 추가를 해주기 때문에 에러발생  
}

class C extends B implements A {  
//실행  
}

interface A { void hello(); }  
interface B { void hi(); }

interface C extends A,B {  
//void hello() { };에러  
void good();  
}

// C implements A,B: A,B를 C에 구현하겠다.

class A { void hello(){ }; }

interface B (implements / extends ?) A{

} //---> 말이 안됨. 클래스를 상속받는 인터페이스는 없다