수업(국비지원)/Java
[Java] chap8 : 인터페이스 - Interface(복합예제)
byeolsub
2023. 4. 15. 23:55
- Interface(복합예제)
jdk8 버전 이후에 인터페이스에서 구현부가 있는 메서드가 가능함
default 메서드 : 객체를 생성할때 인스턴스 메서드.
static 메서드 : 클래스 메서드.
📌
package chap8;
interface MyInterface1{
void method();
default void method1() { //default 메서드. 구현부 존제
System.out.println("MyInterface1의 default 메서드 : method()");
}
static void staticMethod() { //static 메서드. 구현부 존재
System.out.println("MyInterface1의 static 메서드 : staticmethod()");
}
}
interface MyInterface2 {
void method();
default void method1() {
System.out.println("MyInterface2의 default 메서드 : method()");
}
static void staticMethod() {
System.out.println("MyInterface2의 static 메서드 : staticmethod()");
}
}
class Parent {
public void method() {
System.out.println("Parent 클래스의 멤버 메서드 : method");
}
}
//MyInterface1,MyInterface2 인터페이스에 같은 default 메서드가 존재
// => method1() 2개임. => 해당 구현클래스에서 오버라이딩이 필요
//MyInterface1,MyInterface2 인터페이스에 같은 static 메서드가 존재
//static 메서드는 왜 오류가 나지 않을까? - 클래스 멤버여서 객체와는 상관이 없다.
// => 여러개 존재 가능. 인터페이스명.static 메서드명() 호출
class Child extends Parent implements MyInterface1, MyInterface2 {
@Override
public void method1() {
System.out.println("Child의 메서드:method1()");
//MyInterface1 메서드 호출
MyInterface1.super.method1();
}
}
public class InterfaceEx4 {
public static void main(String[] args) {
Child c = new Child();
c.method();
c.method1();
MyInterface1.staticMethod();
}
}