[Java] 인터페이스의 여러가지 요소

sy k·2022년 5월 24일

[Java]객제지향 핵심

목록 보기
14/15
post-thumbnail

📌 상수

  • 인터페이스내 모든 변수는 상수(public static final)로 변환된다.
  • 아래의 예시처럼 static final 선언을 해주지 않아도 자동으로 그렇게 선언된다
double PI = 3.14;
int ERROR = -999999999;

📌 추상 메서드

  • 모든 선언된 메서드는 추상 메서드(public abstract)이다
    즉, 모든 메서드는 선언만하고 구현부가 없으며 자동으로 public abstract선언을 하지 않아도 자동으로 선언된다


📌 디폴트 메서드(자바8 이후)

  • 구현을 가지는 메서드, 인터페이스를 구현하는 클래스들에서 공통으로 사용할 수 있는 기본 메서드
  • default키워드를 사용한다

    디폴트메서드 제공의 이유

    • 특정 인터페이스를 구현하는 클래스가 10개 있다고 하자. 10개의 클래스가 각각 구현하는 번거로운 상황이 생기기 때문에
default void description() {
	System.out.println("정수 계산기를 구현합니다.");
	myMethod();
}
  • 구현하는 클래스에서 재정의 가능
@Override
public void description() {
	System.out.println("CompleteCalc에서 재정의한 default 메서드");
	//super.description();
}
  • 인터페이스를 구현한 클래스의 인스턴스가 생성 되어야 사용 가능함


📌 정적 메서드(자바8 이후)

  • 인스턴스 생성과 상관 없이 인터페이스 타입으로 사용할 수 있는 메서드
    Cal.java(interface)

    static int total(int[] arr) {
    	int total = 0;
    		
    	for(int i: arr) {
    		total += i;
    	}
    	mystaticMethod();
    	return total;
    }
    

    CalculatorTest

  • 아래 예시처럼 new를 하지 않고 배열을 변수로 선언 후에 바로 메소드를 호출해서 사용가능하다.

package ch14;

public class CalculatorTest {

	public static void main(String[] args) {

		Calc calc = new CompleteCalculator();
		int num1 = 10;
		int num2 = 5;
		
		System.out.println(calc.add(num1, num2));
		System.out.println(calc.substract(num1, num2));
		System.out.println(calc.times(num1, num2));
		System.out.println(calc.devide(num1, num2));
		
		calc.description();
		
		int[] arr = {1,2,3,4,5};
		System.out.println(Calc.total(arr));  //정적매소드 바로 호출!
		
	}

}

📌 private 메서드(자바9 이후)

  • 인터페이스를 구현한 클래스에서 사용 혹은 재정의 할 수 없음
  • 오로기 인터페이스 내부에서 사용되기 위해 구현하는 메서드
  • default 메서드나 static 메소드에서 활용함
package ch14;

public interface Calc {
	
	double PI = 3.14;
	int error = -999999999;
	
	int add(int num1, int num2);
	int substract(int num1, int num2);
	int times(int num1, int num2);
	int devide(int num1, int num2);
	
	default void description() {
		System.out.println("정수의 사칙연산을 제공합니다");
		myMethod();  //디폴트 메서드에 사용함
	}
	
	static int total(int[] arr) {
		int total = 0;
		for(int num : arr) {
			total += num;
		}
		myStaticMethod();   // 정적(static) 메소드에 사용함
		return total;
		
	}
	
	private void myMethod() {  //private method
		System.out.println("myPrivateMethod");
	}
	
	private static void myStaticMethod() {  //private method
		System.out.println("myStaticMethod");

	}
	
	
}
profile
개발자가 되고싶어요

0개의 댓글