프로그래밍/Java
[자바/java] 인터페이스
Rolen
2022. 12. 28. 22:53
interface RemoteControl {
void turnOn();
void turnOff();
}
// 인터페이스 사용시 메소드를 구현하지 않으면 에러가 발생한다.
public class Radio implements RemoteControl {
boolean on;
public void turnOn() {
on = true;
System.out.println("라디오가 켜졌습니다.");
}
public void turnOff() {
on = false;
System.out.println("라디오가 꺼졌습니다.");
}
public void status() {
System.out.println("현재의 상태: " +on);
}
public static void main(String[] args) {
Radio r = new Radio();
r.turnOn();
r.turnOff();
r.status();
RemoteControl rr = new Radio();
rr.turnOn();
rr.turnOff();
// rr.status(); // 인터페이스를 자료형으로 사용한 객체이므로 인터페이스에 없는 메소드 사용불가
}
}
interface Drivable {
int NORTH = 1; // 인터페이스 상수 생성
void drive();
default void defaultMethod() { System.out.println("디폴트 메소드는 클래스에서 구현하지 않아도 된다."); }
static void staticPrint() { System.out.println("인터페이스 내에 정적메소드 사용가능."); }
}
interface Flyable { void fly(); }
public class FlyingCar implements Drivable, Flyable {
public void drive() { System.out.println("I'm driving"); }
public void fly() { System.out.println("I'm flying"); }
public void north() { System.out.println(NORTH); } // 상수가 해당 인터페이스를 구현한다면 변수명만 사용가능
public static void main(String[] args) {
FlyingCar car = new FlyingCar();
car.drive();
car.fly();
car.north();
car.defaultMethod();
Drivable.staticPrint();
// car.staticPrint(); // 정적 메소드 - 객체로 불가
}
}
728x90