티스토리 뷰

JAVA/JAVA기본

JAVA - 인터페이스란?

realizers 2022. 1. 26. 16:43
728x90
반응형

인터페이스란?


  • 인터페이스란 메서드에 대한 선언만 한 상태로 모든 메서드를 추상화로 정의한 상태를 말합니다.

 

인터페이스 정의하는 방법


  • 인터페이스는 Interface 키워드와 함께 정의합니다.
  • 인터페이스는 오로지 추상 메서드와 상수만을 포함할 수 있습니다.( Java 8 기준 )
  • 인터페이스는 객체를 생성할 수 없기 때문에 생성자를 가질 수 없습니다.
  • 인터페이스에 선언되어 있는 모든 변수는 public static finl로 선언해야 하며 pubic static final을 생략할 수 있습니다.
  • 인터페이스에 선언되어 있는 모든 메서드는 public abstract로 선언해야 하며 public abstract를 생략할 수 있습니다.
  • 인터페이스에 선언되어 있는 상수는 static {} 블록으로 초기화할 수 없기 때문에 반드시 선언과 동시에 값을 할당해야 합니다.
public interface Eatable {
    public static final String WATER = "삼다수";
    String SOIL = "황토";

    public abstract void eating(String type);
    void drinking(String type);
}

 

인터페이스 구현하는 방법


구현 클래스를 사용하여 구현
  • implements 키워드를 사용하여 인터페이스를 상속받습니다.
  • 인터페이스에 선언된 모든 메서드는 오버라이딩을 해야합니다.
public class Animal implements Eatable{
    @Override
    public void eating(String type) {
        System.out.println(type + "는 먹습니다.");
    }

    @Override
    public void drinking(String type) {
        System.out.println(type + "는 마십니다.");
    }
}

 

익명 구현 객체를 사용하여 구현
  • 보통 구현 클래스를 만드는것이 일반적이지만, 일회성의 객체를 위해서는 비효율적이므로 해당 방법을 사용합니다.
// 인터페이스명 변수명 = new 인터페이스명() {}
Eatable eatable = new Eatable() {}
public class Example {
    public static void main(String[] args) {
        Eatable eatable = new Eatable() {
            @Override
            public void eating(String type) {
                System.out.println(type + "는 먹습니다.");
            }

            @Override
            public void drinking(String type) {
                System.out.println(type + "는 마십니다.");
            }
        };

        eatable.drinking("강아지"); // 강아지는 마십니다.
        eatable.eating("고양이"); // 고양이는 먹습니다.
    }
}

 

인터페이스 레퍼런스를 사용하여 구현
  • 인터페이스는 구현체를 통하여 인스턴스 생성이 가능합니다.
public class Example {
    public static void main(String[] args) {
       Animal cat = new Animal();
       Eatable dog = new Animal();
       
       cat.drinking("고양이"); // 고양이는 마십니다.
       cat.eating("고양이"); // 고양이는 먹습니다.

       dog.drinking("강아지"); // 강아지는 마십니다.
       dog.eating("강아지"); // 강아지는 먹습니다.
    }
}

 

인터페이스 상속


다중 상속
  • 추상 클래스는 다중 상속이 불가능 하지만 인터페이스는 다중 상속이 가능합니다.
public class Animal implements Eatable, Flyable{
    @Override
    public void eating(String type) {
        System.out.println(type + "는 먹습니다.");
    }

    @Override
    public void drinking(String type) {
        System.out.println(type + "는 마십니다.");
    }

    @Override
    public void fly() {
        
    }
}

 

인터페이스 간 상속
public interface Flyable {

    void fly();
}

public interface Eatable extends Flyable{
    public static final String WATER = "삼다수";
    String SOIL = "황토";

    public abstract void eating(String type);
    void drinking(String type);
}

 

인터페이스의 기본 메서드 (Java 8)

Default Method


  • 자바 8이전의 Interface의 메서드는 선언만 가능하며 구현은 할 수 없었습니다. 하지만 8버전 이후부터 Default 메서드를 사용하면 구현부를 가질 수 있습니다.
  • 디폴트 메서드는 인터페이스에서 이미 구현되어 있으므로 구현 클래스에서는 구현하지 않거나 따로 재정의할 수 있습니다.
  • 디폴트 메서드는 인터페이스에 선언되어 있지만 인터페이스에서 바로 사용할 수 없고 구현 객체를 통해 사용할 수 있습니다.
public interface Eatable {
    public static final String WATER = "삼다수";
    String SOIL = "황토";

    public abstract void eating(String type);
    void drinking(String type);

    default void chewable (String type, String name){
        System.out.println(name + "은 씹어먹어야 제맛이지!");
    }
}

public class Animal implements Eatable{
    @Override
    public void eating(String type) {
        System.out.println(type + "는 먹습니다.");
    }

    @Override
    public void drinking(String type) {
        System.out.println(type + "는 마십니다.");
    }

    @Override
    public void chewable(String type, String name) {
        System.out.println(type + "는 " + name + "을 씹는다.");
    }
}

public class Example {
    public static void main(String[] args) {
       Animal dog = new Animal();
       dog.chewable("강아지", "껌"); //강아지는 껌을 씹는다.
    }
}

 

인터페이스의 static 메서드 (Java 8)

static Method


  • 인터페이스명으로 메서들를 호출해야 합니다.
  • public으로 선언이 되지만 생략시 자동으로 할당됩니다.
  • 오버라이딩이 불가능합니다.
public interface Eatable {
    public static final String WATER = "삼다수";
    String SOIL = "황토";

    public abstract void eating(String type);
    void drinking(String type);

    static void biteable (String type){
        System.out.println(type + "는 깨물 수 있습니다.");
    }
}

public class Example {
    public static void main(String[] args) {
       Animal dog = new Animal();
       
        dog.eating("강아지"); // 강아지는 먹습니다.
        // dog.biteable(); 호출 못함 
        Eatable.biteable("고양이"); // 고양이는 깨물 수 있습니다.
    }
}

 

인터페이스의 private 메서드 (Java 9)

private Method


  • default, static 메서드로 인해 인터페이스 내부에 코드를 구현할 수 있게 되면서 외부 구현체에서 필요한 메서드가 아닌 내부에서만 동작되기를 원하는 메서드도 노출되는 경우가 발생하는데 이러한 문제를 해결하기 위해 private 메서드를 지원하여 코드의 중복을 줄이고 내부에서 동작되는 메서드에 대해 캡슐화를 유지할 수 있게 되었습니다.
public interface Eatable {

    void eating(String type);

    static void whatEating(){
        canEatMeet();
    }

    private static void canEatMeet(){
        System.out.println("10KG의 고기를 먹습니다!");
    }
}

public class Animal implements Eatable{

    @Override
    public void eating(String type) {
        System.out.println(type + "는 먹습니다.");
    }
}

public class Example {
    public static void main(String[] args) {
       Animal dog = new Animal();
       
        dog.eating("강아지"); // 강아지는 먹습니다.

        Eatable.whatEating(); // 10KG의 고기를 먹습니다!
    }
}
728x90
반응형