Interface(나머지 부분)

Interface variable

변수들은 모두 자동으로 public static final variable 이 된다. 그렇기 때문에 이 변수들은 클래스의 실채와 상관없이 사용 가능하며 final은 값이 바뀌지 않기 때문에 상수처럼 사용할 수 있게 된 것이라고 생각해 볼 수 있다.

interface Motion{
	int NORTH = 1;
    int EAST = 2;
    int SOUTH = 3;
    int WEST = 4;

    void move(int direction);
    int getX();
    int getY();

}

class TwoDMotion implements Motion {
	private int posX, posY;
	public TwoDMotion() { posX = 0; posY = 0; }

    // 여기와 같이 interface의 변수들이 상수처럼 사용되고 있다.
	public void move(int direction) {
		if(direction == NORTH) posY--;
		else if(direction == SOUTH) posY++;
		else if(direction == EAST) posX++;
		else if(direction == WEST) posX--;
	}

	public int getX() { return posX; }
	public int getY() { return posY; }
}

Interface method

이제 interface의 함수는 abstract 함수라고 하였지만 자바의 버전이 8/9가 되면서 추가적인 다른 형태의 메소드가 나오게 되었다.

static method 이 method는 내부에 구현이 되어 있는 것을 이야기 한다. 우리는 이번에 클래스 객체를 생성하는 메소드인 factory method 에 대해서 언급하고 갈 것이다.

interface IntSequence{

	// 이러한 형태의 메소드를 factory method라고 부른다.
	static IntSequence digitsOf(int n){
		return new DigitSequence(n);
	}
    boolean hasNext();
    int next();
}

이것을 사용하기 위해서는

IntSequence digits = IntSequence.digitsOf(1729);

위와 같이 class method를 호출하여서 바로 사용할 수 있다.

Default method interface 내부에 method에 default 선언도 하고 구현도 해놓는다. 그래서 어떠한 클래스가 interface를 implement하게 되었을때 만약 subtype class가 interface의 default method를 선언하지 않았다면 default method의 기능을 그대로 사용하겠다는 extends로 클래스를 상속받은 것과 비슷한 형태의 결과물이 생기게 된다.목적 : 코드의 중복을 줄이기 위해 예를 들어서 기존의 클래스를 interface로 받는다고 하면 그때마다 새로 함수를 정의해주어야 한다. 그렇기에 상당히 귀찮은 상황이 샐길 수 밖에 없기 때문이다.

intercface IntSequence{
	default boolean hasNext() {return true;}
    int next();
}

//아래와 같이 클래스는 implements 하였지만
//hasNext를 새롭게 정의하지 않았다.
class SquareSequence implements IntSequence{
	private int i;
    public int next(){
		i++;
        return i * i;
    }
}

하지만 한가지 문제점이 생길 수 있다. 만약에 implement를 두 클래스를 받았을 때 똑같은 이름의 메소드를 각 클래스가 모두 가지고 있다면 이때는 문제가 생길 수 있다.

interface Person {
	String getName();
	default int getId() { return 0; }
    // Error: duplicate
    // default methods with the same type of parameters
}

interface Identified {
	default int getId() { return 1; }
    // Error: duplicate
    // default methods with the same type of parameters
}

class Employee implements Person, Identified {
	private String name;
	public Employee(String name) { this.name = name; }
	public String getName() { return this.name; }
}

public class Lecture {
	public static void main(String[] args) {
		Employee m = new Employee("Peter");
        //바로 이부분에서 문제가 생길 수 있다.
		System.out.println(m.getId());
	}
}

  1. 두 클래스 중 하나가 default가 아니라면 문제가 생기지 않을 것이다.