interface printable{ //프린터기와 윈도우를 연결하는 역할을 하는 마소에서 제공하는 인터페이스
//"컴퓨터에서 프린터는 이렇게 돌아가요~"
int WIDTH=800; //인터페이스 내에 선언되는 변수의 특징은 다음과 같습니다.
int HEIGHT=2000; //public, static, final
void print(String doc); //추상메소드 >> body 즉 구현 implement가 빠짐
//모든 메서드는 public이 선언된것으로 간주합니다.
}
class printerA implements printable{ //implement
//삼성에서 만든 프린터 드라이버 ver1
@Override
public void print(String doc) {
System.out.println("printer A");
System.out.println(doc);
}
}
public class Main {
public static void main(String args[]) {
printerA printer1=new printerA();
printer1.print("zzz");
}
}
칼라프린트기가 탄생했다.
1. 인터페이스의 상속
interface printable{
void print(String doc);
void printByColor(String doc);//칼라 프린터기 탄생...! 근데 이래도 되나?
}
class printerA implements printable{//인터페이스를 구현하는 클래스는 모든 추상메소드를 완성해야합니다
//따라서 error 발생..!
//그런데 printerA는 어차피 칼라를 지원 안하는데 어쩌지?
@Override
public void print(String doc) {
System.out.println("printer A");
System.out.println(doc);
}
}
따라서 인터페이스를 다음과 같이 수정합니다.
interface printable{
void print(String doc);
}
interface colorPrintable extends printable{ //인터페이스를 확장. extends함.
void colorPrint(String doc);
}
class printerA implements printable{ //구식 드라이버도 작동합니다
@Override
public void print(String doc) {
System.out.println("printer A");
System.out.println(doc);
}
}
class printerB implements colorPrintable{ //칼라프린터기의 드라이버 새로운 인터페이스와
//그 인터페이스가 상속하는 인터페이스의 모든 추상메소드를 구현해야합니다.
@Override
public void print(String doc) {
// TODO Auto-generated method stub
}
@Override
public void colorPrint(String doc) {
// TODO Auto-generated method stub
}
}
이 문제를 다른방법으로도 해결할 수 있습니다.
2.디폴트 메소드를 추가
interface printable{
void print(String doc);
default void colorPrint(String doc) {};
//디폴트 메소드는 자체로 완전한 메소드입니다. (중괄호가 뒤에 붙음)
//따라서 이를 implement하는 클래스가 꼭 이를 오버라이딩하지 않아도 됩니다.
}
class printerA implements printable{ //구식 드라이버도 작동합니다
@Override
public void print(String doc) {
System.out.println("printer A");
System.out.println(doc);
}
}
class printerB implements printable{
@Override
public void print(String doc) {
// TODO Auto-generated method stub
}
@Override
public void colorPrint(String doc) {
// TODO Auto-generated method stub
}
}
'java' 카테고리의 다른 글
Array 사용법 (0) | 2024.03.13 |
---|---|
Object 클래스 (0) | 2024.03.12 |
super ? 상속의 규칙 (0) | 2024.03.08 |
enhanced for (1) | 2024.03.08 |
배열의 초기화 (0) | 2024.03.08 |