인터페이스란 객체와 객체의 소통 수단이다. 자바에서 다형성을 대표하는 기능 중 하나이다. 인터페이스를 이용하여 다양한 객체를 부속품처럼 사용할 수 있다.
인터페이스의 문법적 특징은 다음과 같다.
1. 실제 기능이 없다. 즉 구현된 기능이 없고 추상메소드와 상속만이 존재한다.
2. 상수를 만들 때 private은 선언해서 안된다.
3. 인터페이스는 객체는 아니지만 객체 타입으로 사용된다.
4. 구현은 실행되는 객체의 메소드에서 실현한다.
package com.Interface;
public interface Interfaces1 { //인터페이스는 추상 메소드와 변수만이 존재, 상속이 존재할 수 있다.
public static String Const_str = "abc"; //상수는 public 취급
public void Func1(); //추상 메소드
}
package com.Interface;
public interface Interfaces2 { //인터페이스는 추상 메소드와 변수만이 존재, 상속이 존재할 수 있다.
public static int Const_Num = 1; //상수는 public 취급
public void Func2(); //추상 메소드
}
package com.Interface;
public class Real_interface implements Interfaces1, Interfaces2 { //인터페이스를 구체화 하는 클래스
public void Func1() { //오버라이드
System.out.println("인터페이스 1에 있습니다.");
}
public void Func2() { //오버라이드
System.out.println("인터페이스 2에 있습니다.");
}
}
package com.Interface;
public class Main {
public static void main(String[] args) {
Real_interface rinter = new Real_interface();
//다형성의 예, 인터페이스는 객체 타입으로 사용
Interfaces1 inter1 = new Real_interface(); //Interfaces1의 함수만 사용할 수 있다.
Interfaces2 inter2 = new Real_interface(); //Interfaces2의 함수만 사용할 수 있다.
rinter.Func1();
rinter.Func2();
System.out.println();
System.out.println(rinter.Const_Num);
System.out.println(rinter.Const_str);
System.out.println();
inter1.Func1();
System.out.println(inter1.Const_str);
System.out.println();
inter2.Func2();
System.out.println(inter2.Const_Num);
}
}
'자바' 카테고리의 다른 글
17. 다중 구현 (0) | 2019.07.29 |
---|---|
16. 핸드폰 예제로 알아보는 인터페이스 (0) | 2019.07.29 |
14. 추상 클래스 (0) | 2019.07.23 |
13. 상속2 (0) | 2019.07.21 |
12. 상속1 (0) | 2019.07.20 |