[ 인터페이스 ]
- JDK 1.7 이전에는 "추상 메소드 + final 상수" 로만 구성된 추상 클래스를 의미한다.
- JDK 1.8 이후로는 "추상 메소드 + default 메소드 + static 메소드 + final 상수" 로 구성된다.
- 1) 추상 메소드 : 본문이 없는 메소드 (대부분은 추상 메소드로 구성됨)
- 2) default 메소드 : 본문이 있는 메소드
- 3) static 메소드 : 클래스 메소드 (본문 있음)
- 인터페이스의 추상 메소드는 public abstract를 생략할 수 있다.
[ 모양 인터페이스 ]
public interface Shape {
// final 상수
public static final double PI = 3.14;
// 추상 메소드
// 추상 메소드는 중괄호대신 세미콜론(;)이 들어간다.
double getArea(); // public abstract 가 생략된 모습
// defalut 메소드
// defalut 로 만들면 객체로 호출할 것 ( 객체.info1() )
public default void info1() {
System.out.println("나는 도형이다.");
}
// static 메소드
// static 로 만들면 클래스로 호출할 것 ( Shape.info2() )
public static void info2() {
System.out.println("나는 도형이다.");
}
}
[ 클래스 상속 vs 인터페이스 구현 ]
- 클래스를 상속 받는다.
- public class Person { }
- public class student extends Person { }
- 인터페이스를 구현한다.
- public interface Shape { }
- public class Rectangle implements Shape { }
- 클래스와 인터페이스는 사실상 같은 것(상속받는 것),
- 말만 다르고(extends 와 implements) 같은 뜻.
[ 사각형 클래스 ]
public class Rectangle implements Shape {
private int width;
private int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
// 인터페이스를 구현한 클래스는 "반드시" 추상 메소드를 오버라이드 해야 한다.
@Override
// int 를 double로 바꾸는 건 자동(promotion)으로 바뀌니 에러안남.
public double getArea() {
return width * height;
}
[ 원 클래스 ]
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return PI * radius * radius;
}
}
[ 메인 메소드 ]
public class MainWrapper {
public static void main(String[] args) {
Shape s1 = new Rectangle(3, 4);
System.out.println(s1.getArea());
s1.info1();
Shape.info2();
Shape s2 = new Circle(1.5);
System.out.println(s2.getArea());
s2.info1();
Shape.info2();
}
}
[ 추가 내용 ]
- 인터페이스를 만들고 클래스에 인터페이스를 구현한다.
- 인터페이스는 다중 인터페이스 구현이 가능하다(Phone, Computer 동시호출)
클래스 상속과 인터페이스 구현을 동시에 할 수 있다.
(상속 먼저 적고, 구현 나중 적기)
public class SmartPhone extends Camera implements Phone, Computer { }