IT 공부/Java

Interface(포함관계)

toraa 2022. 7. 1. 13:07

인터페이스
- 프로그램의 표준화를 위한 방법이다.
- 실제로 구현된것 없이 나중에 구현해서 사용할 기본 설계도이다.
- 구현방법
. class가 아니라 interface로 선언한다. 
. 필드 : 상수만 오직 존재 -> [public static final] int=100;
. 메소드: 추상메서드로 구성 + default, private, static
  > 추상메서드 : [public abstract] void 메서드();


- 객체생성불가 > 구현후에 객체생성이 가능하다.
- 다중상속이 가능하다
- 다중구현이 가능하다


interface A{
	public static final int a=3;
	public abstract void display();
	void print();
	default void a() {}
	private void b() {}
	static void c() {}
}
interface A1 {
	void show();
}
interface A2 extends A,A1 { //다중상속
	void a2();
}
interface A3 {
	void a3();
}
class A4 implements A2,A3 {	//다중구현
	
	@Override
	public void display() {
		System.out.println("난 재정의했어");
	}
	
	@Override
	public void print() {
		System.out.println("나도 재정의된거야");
	}
                                                
	@Override
	public void show() {
		
	}

	@Override
	public void a3() {
		
	}

	@Override
	public void a2() {
		
	}
}


public class InterEx1 {
	public static void main(String[] args) {
		A4 a = new A4();
		a.display();
		a.print();
	}
}
package 포함관계;

interface Lenderable{
	int BORROW = 1;
	int NORMAL = 0;
	void checkIn();
	void checkOut(String borrower, String date);
	
}
class BookLoan implements Lenderable{
	
	String title;
	String date;
	String borrower;
	int status;
	
	public BookLoan(String title) {
		this.title=title;
	}
	
	@Override
	public void checkOut(String borrower, String date) {
		if(status != NORMAL) {
			return;
		}
		this.date =date;
		this.borrower=borrower;
		status=BORROW;
		System.out.println(borrower+"가 "+date+"일에 "+title+"을 대여했습니다.");
	}
	
	@Override
	public void checkIn() {
		if (status!=BORROW) {
			return;
		}
		System.out.println(borrower+"가 "+title+"을 반납하였습니다.");
		title = null;
		borrower = null;
		status = NORMAL;
	}
}

public class InterEx3 {
	public static void main(String[] args) {
		
		BookLoan loan = new BookLoan("젊은 베르테르의 슬픔");
		loan.status = 0; //0 대여가능상태, 1 대여상태
		loan.checkOut("서대길", "2022-07-01");
		loan.checkIn();
	}
}
package 포함관계;

interface Robot{}

class DanceRobot implements Robot{
	void dance() {
		System.out.println("춤을 춥니다.");
	}
}
class DrawRobot implements Robot{
	void draw() {
		System.out.println("그림을 그립니다.");
	}
}
class SingRobot implements Robot{
	void sing() {
		System.out.println("노래를 부릅니다.");
	}
}
public class InterEx5 {
	
	static void action(Robot r) {
		if(r instanceof DanceRobot) {
			((DanceRobot)r).dance();
		}else if(r instanceof DrawRobot) {
			((DrawRobot)r).draw();
		}else if(r instanceof SingRobot) {
			((SingRobot)r).sing();
		}
	}
	public static void main(String[] args) {
		Robot[] rb = new Robot[3];
		rb[0]=new DanceRobot();
		rb[1]=new DrawRobot();
		rb[2]=new SingRobot();
		
		for(Robot r:rb) {
			action(r);
		}		
	}
}