[JAVA] 자바 - 인터페이스(interface)

[JAVA] 자바 - 인터페이스(interface)

728x90

SMALL

인터페이스란?

모든 메서드가 추상 메서드로 선언됩니다. public abstract

모든 변수는 상수로 선언됩니다.

interface 인터페이스 이름 { public static final float pi = 3.14F; public void makeSomething(); }

자바 8부터 디폴트 메서드(default method)와 정적 메서드(static method) 기능의 제공으로 일부 구현 코드가 있습니다.

인터페이스 정의와 구현하기

선언된 메서드들은 당연히 구현코드가 없습니다.

public interface Calc { double PI = 3.14; int ERROR = -9999999; int add(int num1, int num2); int substract(int num1, int num2); int times(int num1, int num2); int divide(int num1, int num2); }

Calculator.java

public abstract class Calculator implements Calc { // 4개의 메서드를 다 구현하지 않기 때문에 abstract가 되어야 합니다. @Override public int add(int num1, int num2) { return num1 + num2; } @Override public int substract(int num1, int num2) { return num1 - num2; } }

CompleteCalc.java

public class CompleteCalc extends Calculator { @Override public int times(int num1, int num2) { return num1 * num2; } @Override public int divide(int num1, int num2) { if(num2 == 0) { return ERROR; } return num1 / num2; } public void showInfo() { System.out.println("모두 구현"); } }

CalculatorTest.java

public class CalculatorTest { public static void main(String[] args) { int n1 = 10; int n2 = 2; Calc calc = new CompleteCalc(); System.out.println(calc.add(n1, n2)); System.out.println(calc.substract(n1, n2)); System.out.println(calc.times(n1, n2)); System.out.println(calc.divide(n1, n2)); } }

출력 결과

12 8 20 5

인터페이스 구현과 형 변환

인터페이스를 구현한 클래스는 인터페이스 형으로 선언한 변수로 형 변환할 수 있습니다.

Calc calc = new CompleteCalc();

상속에서의 형 변환과 동일한 의미입니다.

클래스 상속과 달리 구현 코드가 없으므로 여러 인터페이스를 구현할 수 있습니다. (cf. extends)

형 변환되는 경우 인터페이스에 선언된 메서드만을 사용 가능합니다.

https://github.com/Seong-Jun1525/JavaStudy#%EC%9D%B8%ED%84%B0%ED%8E%98%EC%9D%B4%EC%8A%A4interface

728x90

LIST

from http://seong-jun.tistory.com/39 by ccl(A) rewrite - 2021-12-01 11:27:46