[Java] Interface

immanuelk1m·2023년 6월 5일
0

Java

목록 보기
2/9
post-thumbnail

Interface란??

A "contract" that spells out how software developed by different groups of
programmers interacts

서로 다른 프로그래머에 의해 개발된 소프트웨어가 어떻게 상호 작용하는지 설명하는 계약

Interface in Java

Java에서 Interface는 다른 그룹의 코드가 어떻게 작성되었는지 몰라도 Interface 형식에 맞게 자신의 코드를 작성할 수 있다.

Contains

  • constants
  • method signatures (method name과 parameters)
  • default methods // method body 작성
  • static methods // method body 작성
  • nested types

Implement

Interface는 인스턴스화 할 수 없고 class에 implements한 후 사용해야 한다.

public class OperateBMW760i implements OperateCar

Define

Interface Header

interface 정의 부분은 modifiers, the keyword 'interface', interface 이름, a comma-separated list of parent interfaces 로 구성된다.

public interface GroupedInterface extends Interface1, Interface2, Interface3 
{

}

Naming convention

Interface 이름을 짓는 방식에는 크게 3가지가 있다.

  • Adjective Form : Iterable, Computable
  • Noun Form : Map, List
  • prefix 'I' ~ : ICar, ICalculator

Interface Body

Interface Body 부분에는 크게 4가지를 작성할 수 있다.

  • method signatures (=abstract methods)
    : method signatures 작성 시 implementation 부분은 따로 작성해주지 않아도 된다

  • default methods
    defined with the 'default' modifier

  • static methods.
    defined with the 'static' keyword.

  • constant values

모든 interface 내에 있는 abstract, default, and static methods는 public이므로, modifier 부분을 생략해도 된다.

public interface ExampleInterface {
    int MAX_VALUE = 100; // 상수 선언

    void abstractMethod(); // 추상 메소드 선언

    default void defaultMethod() {
        System.out.println("This is a default method."); // default 메소드 구현
    }

    static void staticMethod() {
        System.out.println("This is a static method."); // static 메소드 구현
    }
}

Interface as a Type

Interface는 하나의 reference data type이므로 interface 이름으로 type 선언이 가능하다.

Interface type을 가진 reference variable를 새로 만들 때, 이 Object는 해당 Interface를 구현하는 Class의 instance여야만 한다.

// Relatable interface를 가지고 있는 object1,2
public Object findLargest(Object object1, Object object2) 
{
   Relatable obj1 = (Relatable)object1;
   Relatable obj2 = (Relatable)object2;
   // relatable type으로 type casting 
   
   if ((obj1).isLargerThan(obj2) > 0)
      return object1;
   else 
      return object2;
}

object1과 object2는 interface 타입인 Relatable type으로 casting 될 수 있고, isLargerThan method를 사용할 수 있다.

isLargerThan 메소드는 Relatable 인터페이스를 구현한 객체라면 어떠한 객체든지 사용할 수 있다. 그리고 이런 객체는 자기 자신의 타입과 Relatable 타입 두개를 가질 수 있다. 즉 이를 통해 구현 객체의 타입에 의존없이 interface 타입에서 동작하도록 할 수 있으므로 multiple inheritance의 장점을 이용할 수 있다.

Envoling Interface

Java Program이 다 만들어진 상태에서 Interface에 새로운 Method를 추가하게 되면
시스템 전체의 Interface를 수정해 주어야 한다.

public interface DoIt 
{
  void doSomething(int i, double x);
  int doSomethingElse(String s);
}

==>>

public interface DoIt 
{
  void doSomething(int i, double x);
  int doSomethingElse(String s);
  boolean didItWork(int i, double x, String s);
}

이러한 경우에는 어떻게 해야할까??

Extend

가장 쉬운 방법으로는 기존 DoIt Method를 상속 받는 새로운 Interface를 선언해
추가 / 변경할 부분만 수정한다.

public interface DoItPlus extends DoIt 
{
	boolean didItWork(int i, double x, String s);
}

Default Method

또 다른 방법으로는 Default Method를 선언해 함수 내용을 implement를 작성해주는 방법이 있다.

public interface DoIt 
{
  void doSomething(int i, double x);
  int doSomethingElse(String s);
  
  default boolean didItWork(int i, double x, String s) 
  {
  	// Method body ... (actually implemented method.)
  }
}
Default vs Static

Default는 인터페이스에 새로운 기능을 추가하면서도, 이전 버전의 코드와 호환되도록 유지할 수 있는 방법으로, 기존에 작성된 코드를 수정하지 않고도 새로운 기능을 사용할 수 있다.

반면 Static은 utility methods로 interface를 구성하는 핵심 method가 아니다.

Extending Interfaces that Contain Default Methods

interface를 extend 할 때, default method가 포함 된 경우
3가지 경우를 고려할 수 있다.

  • 상속 받은 default method를 따로 다루지 않는 경우 => 그대로 사용
  • 상속 받은 default method를 재선언 하는 경우 => abstract method로 변경
  • 상속 받은 default method를 재정의 하는 경우 => Overriding
profile
개발 새발

0개의 댓글