자바의 정석 7장 (16일차) - 인터페이스

728x90

인터페이스

정의:

  • 추상메서드의 집합
  • 구현된 것이 전혀 없는 설계도 껍데기
  • 모든 멤버가 public static final & public abstract이여야 함
  • 따라서 public static final과 public abstract는 인터페이스 내에서 생략이 가능하다

추상메서드와 인터페이스의 차이점

  • 추상메서드는 생성자, IV, 추상메서드를 가지고 있지만 인터페이스는 찐으로 아무것도 없는 빈 깡통
  • IV의 보유 여부로 판별 가능 = 인터페이스 IV 없음, 추상 메서드 IV 존재 
    • 다만 상수는 가질 수 있음 = final

인터페이스 선언하는 법

클래스와 동일하게 생성

위의 설명과 같이 앞의 public static final 은 interface에서 필수로 적용되야하기 때문에 생략이 가능하다

interface interfacetest{
	public static final String shape = "squre";
	static String cardkind = "diamond";
	final int Heart = 2;
	int clover = 5; //부분적 생략 or 전부다 생략가능
}

interface cardgame{
	public abstract void shuffle();
	void pick(); // public abstract 생략 가능
}

 

인터페이스의 상속

  • 인터페이스의 조상은 인터페이스만 가능 (다른 클래스 상속과 다르게 object가 최고 조상이 될 수 없음)
  • 다중 상속이 가능 (추상메서드는 선언부는 전부 동일하고 구성하는 메서드 IV가 없으므로 충돌할 변수가 없음)

 

interface card extends cardgame, CardScore{ //충돌할 변수들이 없기 때문에 다중상속 가능함
	public static final String shape = "squre";
	static String cardkind = "diamond";
	final int Heart = 2;
	int clover = 5; //부분적 생략 or 전부다 생략가능
}
interface cardgame{
	public abstract void shuffle();
	void pick(); // public abstract 생략 가능
}
interface CardScore{
	int totalScore = 0;
	void CardScoreCalculator();
}

 

인터페이스의 구현

  • 인터페이스에 정의된 모든 메서드를 구현해야함 (결국 추상메서드의 집합, 즉 미완성된 설계도의 집합)
  • 상속을 통해 완성시켜야 하는데 implements 함수를 사용하여 구현을 완성해야 함
interface cardgame{
	ArrayList<Integer> diamond = new ArrayList<>();
}

interface CardScore{
	int totalScore = 0;
	
	void CardScoreCalculator();
}

class cardnumber implements cardgame{ //카드게임의 추상메서드를 구현
	public void numberscounting() {
		for(int i = 1; i<11; i++) {
			diamond.add(i);
			System.out.println(diamond.get(i));
		}
	}
}

 

  • 일부만 구현하는 경우 아래와 같이 abstract를 붙여야 오류가 나지 않음
  • 일부만 구현하여 의미있는 순서대로 인터페이스를 구현하다보면 나중에 유지보수가 편하고 가독성이 좋아짐
interface cardgame{
	ArrayList<Integer> diamond = new ArrayList<>();
	
	public abstract void shuffle();
	void pick(); // public abstract 생략 가능
}

interface CardScore{
	int totalScore = 0;
	
	void CardScoreCalculator();
}

abstract class cardnumber implements cardgame{ //메서드 총 3개 중 2개만 구현하였기 때문에 abstract화
	public void numberscounting() {
		for(int i = 1; i<11; i++) {
			diamond.add(i);
			System.out.println(diamond.get(i));
		}
	}
}
728x90