인터페이스란?
클래스와 달리 객체를 생성할 수 없고
1) 다양한 자료형의 객체를 위해 (확장성)
2) 객체를 계속 새로 만들 필요 없이 인터페이스에서 선언만 한 메소드를
인터페이스를 implements 한 클래스에서 구현할 수 있기 때문에 다양한 기능을 가진 객체를 생성 가능
-> '클래스에서 인터페이스를 구현한다' 라고 함
예제 1)
인터페이스 A,B
public interface interfaceA {
// 인터페이스는 메소드를 선언만 하고 정의하지는 않는다
// 구현하는 클래스에서 오버라이드
public void funA();
}
public interface interfaceB {
public void funB();
}
인터페이스를 implements한 클래스
//다형성 여러 인터페이스를 구현할 수 있음
public class No10_Interface implements interfaceA, interfaceB {
public No10_Interface() {
System.out.println("--interface constructor--");
}
// implements 한 이 클래스에서 인터페이스 오버라이드
@Override
public void funA() {
System.out.println("--functionA--");
}
@Override
public void funB() {
System.out.println("--functionA--");
}
}
실행클래스
public class No10_Interface_Ex {
public static void main(String[] args) {
// 인터페이스 클래스를 통해 객체생성
interfaceA iA = new No10_Interface();
interfaceB iB = new No10_Interface();
System.out.println();
iA.funA();
iB.funB();
}
}
예제2)
인터페이스
public interface Toy {
public void walk();
public void run();
public void alarm();
public void light();
}
인터페이스 implements한 클래스 1
public class No10_Interface_Toy_Airplane implements Toy{
public No10_Interface_Toy_Airplane() {
System.out.println("--- Toy Interface Constructor---1");
}
@Override
public void walk() {
System.out.println("airplane cannot walk");
}
@Override
public void run() {
System.out.println("airplane cannot run");
}
@Override
public void alarm() {
System.out.println("airplane has alarm function");
}
@Override
public void light() {
System.out.println("airplane has light function");
}
}
인터페이스 implements한 클래스 2
public class No10_Interface_Toy_Robot implements Toy{
public No10_Interface_Toy_Robot() {
System.out.println("--- Toy Interface Constructor---2");
}
@Override
public void walk() {
System.out.println("robot can walk");
}
@Override
public void run() {
System.out.println("robot can run");
}
@Override
public void alarm() {
System.out.println("robot has alarm system");
}
@Override
public void light() {
System.out.println("robot gas light system");
}
}
실행클래스
public class No10_Interface_Toy_Ex {
public static void main(String[] args) {
// No10_Interface_Toy_Airplane airplane = new No10_Interface_Toy_Airplane();
// No10_Interface_Toy_Robot robot = new No10_Interface_Toy_Robot();
// 인터페이스 객체생성
Toy airplane = new No10_Interface_Toy_Airplane();
Toy robot = new No10_Interface_Toy_Robot();
// 배열에 넣을 수 있음, 데이터타입이 Toy로 같아서 가능
Toy toys[] = {airplane, robot};
for(int i=0; i<toys.length; i++) {
toys[i].walk();
toys[i].run();
toys[i].alarm();
toys[i].light();
System.out.println();
}
}
}
'Java' 카테고리의 다른 글
[Java] 추상클래스 (0) | 2021.07.29 |
---|---|
[Java] 비트연산 (0) | 2021.07.29 |
[Java] 내부클래스, 익명클래스 (0) | 2021.07.27 |
[Java] 상속 메소드 오버라이드, 자료형, super 클래스 (0) | 2021.07.24 |
[Java] static과 private, Getter&Setter (0) | 2021.07.24 |