본문 바로가기

Backend/Java

[인프런] 인터페이스, 문법, 개념

예제로 공부하는 Java 100 문제풀이 Part.4

 

[1]: 인터페이스
추상 클래스와 거의 비슷하나 그 추상화 정도가 더 높다.(더 엄격) --> 일반 메서드나 멤버 필드(변수)를 가질 수 없다.
표준화 및 규격을 인터페이스로 제공 --> 일종의 "설계도" 개념.
따라서 어떤 클래스가 해당 인터페이스를 사용(상속)한다면 인터페이스에 선언되어져 있는 메서드를 구현.
인터페이스는 interface 키워드를 사용한다.
추상 클래스와 같이 메서드의 구체적인 내용은 기술되어져 있지 않으므로 인터페이스를 상속받은 클래스에서 재정의(오버라이딩)하여 사용.

[2]: 상속
클래스는 "단일 상속"만 가능, 인터페이스는 "다중 상속"이 가능 --> 가장 큰 차이점.
class --> extends    interface --> implements
즉, 이를 이용하면 여러 개의 인터페이스로부터 메서드를 받아올 수 있게 된다. (다중 상속 구현)

[3]: 장점
인터페이스를 이용하면 메서드의 추상적인 "선언"과 그 메서드들을 구체적인 "구현" 부분을 분리시킬 수 있다. --> 매우 큰 장점.

[4]: 우선 순위 (extends vs implements)
상속을 받는 extends 키워드와 구현을 하는 implements 키워드가 동시에 쓰일 때 --> extends 키워드가 항상 먼저 쓰인다.
ex) class Student extends Person implemets A, B

 

package java100;

class Persons{
	// Field
	String name;
	int age;
	int weight;
	
	// Constructor
	Persons(){}
	Persons(String name, int age, int weight){
		this.name = name;
		this.age = age;
		this.weight = weight;
	}
	// Method
	void wash() {System.out.println("씻다.");}
	void study() {System.out.println("공부하다.");}
	void play() {System.out.println("놀다.");}
}

interface Allowance{
	// Field
	// 변수는 안 되나 상수는 되므로 상수로 지정해주면 됨 --> public static final을 붙여주면 됨.
	// 인터페이스 내의 모든 멤버 필드(변수)는 public static final이어야 함 --> 생략이 가능 --> 그냥 "타입 상수명" 지정해서 쓰면 됨.
	public static final String aaa = "코리아";
	int bbb = 100;
	
	// Abstract Method
	// 인터페이스 내의 모든 메서드는 public abstract이어야 함 --> 생략이 가능.
	public abstract void in(int price, String name);
	abstract void out(int price, String name);
}

interface Train{
	abstract void train(int training_pay, String name);
}

class Students extends Persons implements Allowance, Train{
	// Field
	
	// Constructor
	Students(){}
	Students(String name, int age, int weight){
		super(name,age,weight);
	}
	
	// Method
	public void in(int price, String name) {System.out.printf("%s에게서 %d원 용돈을 받았습니다.%n",name, price);}
	public void out(int price, String name) {System.out.printf("%d원 금액을 지출했습니다. [지출 용도 --> %s]%n",price, name);}
	public void train(int training_pay, String name) {System.out.printf("[%s --> %d원 입금 완료]%n",name, training_pay);}
}


public class Java100_Ex37 {

	public static void main(String[] args) {
		
		// [1]: 객체 생성
		Students s1 = new Students("홍길동",20,85);
		
		//[2]: 클래스와 인터페이스로부터 상속과 구현을 메서드들 호출하기
		s1.wash(); //상속
		s1.study(); //상속
		s1.play(); //상속
		s1.in(10000, "엄마"); //구현
		s1.out(5000, "편의점"); //구현
		s1.train(50000, "아빠"); //구현
		
		//[3]: 상수 필드 사용하기
		System.out.println(s1.aaa);
		System.out.println(s1.bbb);
		System.out.println(Allowance.aaa);
		System.out.println(Allowance.bbb);
	}

}