원래 자바에서는 클래스 두 개 상속 받는 게 금기시 된다. 추상클래스도 안 됨 근데 인터페이스 클래스는 가능함 유일하게 가능하다.
interface Interface1{
int interVar = 10;
void interface1Method();
}
class Interface1Impl implements Interface1{
@Override
public void interface1Method() {
System.out.println("interface1Method 구현");
}
}
public class InterfaceTest1 {
public static void main(String[] args) {
Interface1Impl in1Impl = new Interface1Impl();
System.out.println("in1Impl.interVar = " + in1Impl.interVar);
System.out.println("Interface1.interVar = " + Interface1.interVar);
in1Impl.interface1Method();
}
}
class Vehicle1{
void move() {
System.out.println("움직인다.");
}
}
interface Flyable{
void fly();
}
class Interface2Impl extends Vehicle1 implements Flyable{
@Override
public void fly() {
System.out.println("난다.");
}
}
public class InterfaceTest2 {
public static void main(String[] args) {
Interface2Impl in2Impl = new Interface2Impl();
in2Impl.fly();
in2Impl.move();
}
}
interface In1{
int x = 10; //상수
void in1Method(); //추상메소드
}
interface In2{
int x = 20;
void in1Method();
void in2Method();
}
interface In3 extends In1, In2{
//인터페이스 클래스 두 개 상속
//구현을 안 하고 나도 인터페이스다 선언
//일반 클래스였다면 implements 해줬어야 했다.
}
class ImplementsTest implements In3{
//두개의 상속을 하지 않고 In3 하나만 가져와도 됨
@Override
public void in1Method() {
}
@Override
public void in2Method() {
}
//내용이 없지만 구현이 된 것이다.
}
public class InterfaceTest3 {
public static void main(String[] args) {
ImplementsTest it = new ImplementsTest();
it.in1Method();
it.in2Method();
System.out.println(In1.x);
System.out.println(In2.x);
}
}
interface In3 extends In1, In2{
//인터페이스 클래스 두 개 상속
//구현을 안 하고 나도 인터페이스다 선언
//일반 클래스였다면 implements 해줬어야 했다.
}
클래스 2개 이상 상속을 받는다. (=다중 상속)
내용이 없어도 선언과 밑에 구현은 다 돼 있음
'개발일지 > Java + Spring' 카테고리의 다른 글
클래스 이용해서 학점 계산하기_진짜_최종.java (0) | 2021.10.14 |
---|---|
예외처리(try-catch) (0) | 2021.10.14 |
데이터베이스 자바에서 연결하기 (0) | 2021.10.08 |
[Java] File 만들기/읽기 (0) | 2021.09.30 |
[Java] 거스름 돈 출력 - 예제 (0) | 2021.09.30 |