본문 바로가기

Java

Java- interface

인터페이스

  인터페이스는 추상메소드를 담고 있는 완전추상클래스 비슷한 놈으로 이해하자. 참고로 이놈은 추상메소드만 가지기 때문에 메소드의 몸체는 구현하지 않는다.

  또한 몇가지 특징이 있는데...

  • 인터페이스의 메소드는 자동으로 public 선언된다.
  • 인터페이스의 변수public static final 선언된다.(인스턴스 없이도 호출가능한 상수취급임) 

 인터페이스 참조변수의 선언

  • 인터페이스 형 참조변수의 구현도 가능하다.
  • 또한 인터페이스 참조 변수는 자신을 구현한 클래스 인스턴스의 참조도 가능하다.
  • 즉슨, 인터페이스 메소드의 오버라이딩도 가능하다.

 implements 키워드

  인터페이스를 구현한 클래스는 인터페이스 내부의 모든 메소드를 구현해야한다. 또한 인터페이스를 클래스에 구현할 때에는 implements 키워드를 사용한다. 그런데 인터페이스간 상속시에는 extends 키워드를 사용한다.

 

  • 클래스에서 인터페이스의 구현시에만 implements를 사용
  • 클래스와 클래스, 인터페이스와 인터페이스간에는 extends 사용

 인터페이스 구현 꿀팁

  이건 꿀팁인데, 처음 인터페이스를 구현할때 인터페이스 관련 메소드를 구현하지 않았을때, 

"class 클래스명 implements 인터페이스명"{ } 이런 상태에서 구현 안됐다고 빨간줄이 뜰텐데 그 때 빨간줄 클릭하면  메소드 구현이라고 버튼이 뜬다. 그거 누르면 메소드 구조를 자기가 알아서 만들어줌.

메서드 구현 누르면 완성!

 

interface WHPrinter{  //흑백프린터 전용 인터페이스
    String InkType = "Black";  //상수라서 대문자 시작(public static final String InkType)

    void whPrint(String doc);  //인터페이스 메소드
}
interface CoPrinter extends WHPrinter{  //컬러 프린터 인터페이스(WHPrinter 상속)
    String TonnerType = "Laser";

    void coPrint(String doc);
}

class LGPrinter implements WHPrinter{  //WHPrinter 구현한 클래스
    @Override  //인터페이스 메소드의 오버라이딩
    public void whPrint(String doc) {
        System.out.println("<LG>");
        System.out.println("inkType: "+InkType);
        System.out.println("white&black print>>"+doc+"\n");
    }
}
class SamsungPrinter implements CoPrinter{  //CoPrinter 구현한 클래스
    @Override
    public void whPrint(String doc) {
        System.out.println("<SamSung>");
        System.out.println("inkType: "+InkType);
        System.out.println("white&black print>>"+doc+"\n");
    }

    @Override
    public void coPrint(String doc) {
        System.out.println("<SamSung>");
        System.out.println("tonnerType: "+ TonnerType);
        System.out.println("color print>>"+doc+"\n");
    }
}

public class InterfacePractice {
    public static void main(String[] args) {
        String doc = "This is document....";

        WHPrinter whPrn = new LGPrinter();
        whPrn.whPrint(doc);

        CoPrinter coPrn = new SamsungPrinter();
        coPrn.whPrint(doc);
        coPrn.coPrint(doc);
    }
}


<LG>
inkType: Black
white&black print>>This is document....

<SamSung>
inkType: Black
white&black print>>This is document....

<SamSung>
tonnerType: Laser
color print>>This is document....

 디폴트 메소드

  인터페이스는 기능에 대한 선언만 가능하기 때문에, 실제 코드를 구현한 로직은 포함될 수 없다. 하지만 자바8에서 이러한 룰을 깨트리는 기능이 나오게 되었는 데 그것이 Default Method(디폴트 메소드)이다. 메소드 선언 시에 default를 명시하게 되면 인터페이스 내부에서도 로직이 포함된 메소드를 선언할 수 있다.

 

  먼저 어떠한 소스코드를 완성을 한 상황이라고 가정을 하자. 그런 상황에서 추가적인 기능을 구현하고 싶어서 추가를 한다고 가정하자. 그렇다면 기존 인터페이스의 메소드를 추가하려면 각 인터페이스에 새로운 인터페이스를 상속하여야 한다. 이 경우 만일 인터페이스의 수가 너무 많은 경우 굉장히 힘든 일이 될 것이다. 

 따라서 그러한 경우에는 디폴트 메소드를 사용한다. 디폴트 메소드는 이전에 개발해 놓은 코드에 영향을 미치지 않기 위해서 등장한 문법이다.

interface Printerable{
    void print(String doc);
    default void colorPrint(String doc){  //추후에 추가한 디폴트 메소드
        System.out.println("color print>>> "+doc);  //디폴트 메소드는 내부 로직이 구현되어있다( == 오버라이딩 안해도 됨)
    }
}
class SamSungPrinter implements Printerable{

    @Override
    public void print(String doc) {
        System.out.println("white&black print>>> "+doc);
    }
}
public class PrinterDriver4 {
    public static void main(String[] args) {
        String doc = "This is document....";

        SamSungPrinter sam = new SamSungPrinter();
        sam.print(doc);
        sam.colorPrint(doc);
    }
}


white&black print>>> This is document....
color print>>> This is document....

 인터페이스의 static 메소드

  인터페이스에도 클래스처럼 static 선언을 통한 클래스 메소드의 구현이 가능하다.

interface inter{
    static void classMethod(){
        //클래스 메소드. 인스턴스 생성전에 인터페이스 이름으로 접근하여 사용이 가능
        System.out.println("classMethod");
    }
}

public class InterfacePractice {
    public static void main(String[] args) {
        inter.classMethod();  //인터페이스 명으로 접근
    }
}

classMethod

'Java' 카테고리의 다른 글

Java- 예외처리  (0) 2023.01.02
Java- 인터페이스와 추상클래스 비교  (0) 2023.01.01
Java- Object 클래스  (0) 2022.12.29
Java- 상속  (0) 2022.12.29
Java- 배열  (0) 2022.12.27