JAVA

[Java] 인터페이스(Interface)

yujin0517 2024. 2. 13. 20:17

인터페이스(Interface)

인터페이스는 사용자 간 또는 컴퓨터 간 '통신'이 가능하도록 연결해주는 디바이스나 프로그램을 의미합니다.

사용자 간, 컴퓨터 간 통신을 위해서는 '규격'이 중요합니다. 여기서 '규격'은 인터페이스라 할 수 있고, 인터페이스는 하나의 '표준화'를 제공하는 것이라 할 수 있습니다. 

인터페이스라는 개념은 추상 클래스와 매우 유사합니다. 쉽게 말해 인터페이스는 추상 클래스보다 추상화 정도가 더 높은 개념이라고 생각하면 됩니다. 

또, 하나의 차이점은 인터페이스는 일반 메소드나 멤버 필드를 가질 수 없습니다. 

 

어떤 클래스가 인터페이스를 사용한다면(상속받는다면) 인터페이스에 선언되어 있는 메소드 구현해야 한다. 

인터페이스를 선언할 때, class 키워드가 아닌 'interface 키워드'를 사용하고, 

인터페이스를 상속받을 때, extends 카워드가 아닌 'implements 키워드'를 사용해야 합니다. 

 

클래스와 인터페이스의 가장 큰 차이점은 '상속'입니다. 

일반 클래스는 단일 상속만 가능하지만 인터페이스는 '다중 상속'이 가능합니다. 

인터페이스는 '구현'의 의미를 강조하기 위해 extends 키워드를 사용하지 않고 implements 키워드를 사용하여 다중 상속을 구현합니다. (우선순위는 extends > implements입니다.) 

 

이러한 특징이 있는 인터페이스의 장점은 '분업화'에 있습니다. 

인터페이스를 이용하면 메소드의 추상적인 선언과 메소드들의 구현 부분을 분리시킬 수 있기 때문입니다. 


인터페이스 특징

  • 추상화
  • 다중 상속
  • 다형성
  • 느슨한 결합
  • API 설계: 클라이언트가 API를 사용할 때 준수해야 하는 내용을 정의하여 일관성 있는 규칙을 제공한다. 인터페이스를 사용하면 인터페이스에 의존하는 클라이언트에 영향을 주지 않고 새로운 구현을 개발할 수 있기 때문에 기존 코드를 중단하지 않고 API를 확장할 수 있다. 

사용법

interface Person {
	public static final String name = "choi"; //public static final 생략가능
	public static final int age = 22; //public static final 생략가능
	
	//추상 메소드 선언
}

인터페이스 필드는 상수로 지정해줘야 합니다. 때문에 타입 선언 앞에 'public static final'를 적어줘야 합니다. 

하지만 인터페이스를 사용할 때 타입 선언 앞에 항상 'public static final'이 사용되기 때문에 생략 가능합니다. 

즉, 일반 변수처럼 선언하여 사용하면 됩니다. 다만 상수를 사용해야 한다는 점을 알아 둬야 합니다. 

class Student implements Person {
	//필드
	//추상 메소드 구현
}

인터페이스는 객체 생성 없이 메인 클래스에서 필드를 사용할 수 있습니다. 

System.out.println(Person.name); //choi 출력됨
System.out.println(Person.age); //22 출력됨

 


 

예시1

class Person { //부모클래스1
	String name;
	int age;
	int height;
	
	Person(){}
	Person(String name, int age, int height){
		this.name = name;
		this.age = age;
		this.height = height;
	}
	
	void wash() {System.out.println("Washing!");}
	void study() {System.out.println("Studying!");}
	void play() {System.out.println("Playing!");}
}

//인터페이스 -> 일반 메소드 사용 불가 
interface Allowance { //부모클래스2, interface 
	//변수는 안되나 상수는 되므로 상수로 지정해주면 됨 -> public static final -> 항상 붙기때문에 생략가능
	public static final String a = "korean";
	int b = 100; //컴파일 과정에서 public static final을 붙여줌.	
	
	//추상메소드만 사용가능! abstract 키워드 생략가능
	//private 사용 안됨 -> 자식클래스에서 재정의 해야하기 때문에 public으로 지정
	abstract void in(int price, String name);
	abstract void out(int price, String name);
}

interface Train { //부모클래스3, interface
	abstract void train(int training_pay, String name);
}

class Student extends Person implements Allowance, Train { //자식클래스, 다중상속

	Student(){}
	Student(String name, int age, int height){
		super(name, age, height);
	}
	
	public void in(int price, String name) {System.out.println(name + " -> give me : " + price);}
	public void out(int price, String name) {System.out.println("me -> give " + name + " : " + price);}
	public void train(int training_pay, String name) {System.out.println(training_pay + "won give " + name);}
}

public class Main {
	public static void main(String[] args) {
		Student s1 = new Student("choi", 22, 60);

		System.out.println("Name: " + s1.name);
		System.out.println("Age: " + s1.age);
		s1.study();
		System.out.println("-----------------------------");
		
		s1.in(1000, "friends");
		s1.out(2000, "store");
		s1.train(50000, "gim");
		System.out.println("-----------------------------");
		
		//객체 생성없이 필드를 사용할 수 있다. 
		System.out.println(Allowance.a);
		System.out.println(Allowance.b);
	}
}

 

콘솔1


예시2

public interface CafeCustomer {
	public String customerMenu();
}

public class CafeCustomerA implements CafeCustomer {
	@Override
	public String customerMenu() {
		return "손님 A가 아메리카노를 주문했습니다.";
	}
}
public class CafeCustomerB implements CafeCustomer {
	@Override
	public String customerMenu() {
		return "손님 B가 딸리라떼를 주문했습니다.";
	}
}

public class CafeOwner {
	public void giveMenu(CafeCustomer cus) {
		System.out.println(cus.customerMenu());
	}
}

public class CafeOrder {
	public static void main(String[] args) {
		CafeOwner owner = new CafeOwner();
		CafeCustomerA a = new CafeCustomerA();
		CafeCustomerB b = new CafeCustomerB();
		
		owner.giveMenu(a);
		owner.giveMenu(b);
	}
}

 

콘솔2

 


 

요약

인터페이스는 상호 간의 통신을 위해 표준화를 제공한다. 

  • class 키워드 대신 interface 키워드, extends 키워드 대신 implements 키워드를 사용한다. 
  • 인터페이스와 추상 클래스는 유사하나 인터페이스가 추상 클래스보다 추상화 정도가 더 높다. 
  • 인터페이스에는 일반 메소드나 멤버 필드를 사용할 수 없다. 
  • 인터페이스는 다중 상속이 가능하다. 
  • 우선순위는 extends 키워드가 implements 키워드보다 높다. 
  • 분업화 시스템을 만들 때 용이하게 사용된다. 

 

2022.08.24

 

감사합니다!

'JAVA' 카테고리의 다른 글

MVC 패턴, MVC 패턴의 한계  (0) 2024.02.08
JSP와 서블릿(Servlet) 그리고 MVC 패턴  (1) 2024.02.06
스레드 풀(Thread Pool)과 Executor  (0) 2024.01.31
스레드(Thread)  (1) 2024.01.27
소수 찾기, 구하기  (0) 2023.02.01