본문 바로가기
개발 수업/JAVA

[Java] 인터페이스 예제

by 오늘 하루s 2023. 5. 18.
728x90
더보기

Day15-3. 230518

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package chap0607;
 
//Polymorphism(다형성)_매개변수의 다형성
class BusP393 implements Vehicle{
    @Override
    public void run() {
        System.out.println("Bus-run()");
    }
}
class TaxiP393 implements Vehicle{
    @Override
    public void run() {
        System.out.println("Taxi-run()");
    }
}
 
public class Polymorphism_p394 {
    public static void main(String[] args) {
        DriverP393 driver = new DriverP393();
        //driver.drive(new Vehicle()); //에러발생.인터페이스는 생성자가 없다.
        
        BusP393 bus = new BusP393();
        driver.drive(bus); //Bus-run()
        
        TaxiP393 taxi = new TaxiP393();
        driver.drive(taxi); //Taxi-run()
        
        //driver.drive(new Car05());//에러발생
    }
}
 
class DriverP393{
    //drive()메서드에는 interface Vehicle 참조하는 매개변수가 있다.
    void drive(Vehicle vehicle) {
        vehicle.run();
    }
}
cs

 

1
2
3
4
5
6
7
8
9
package chap0607;
 
public interface Vehicle {
    //인터페이스에는 생성자가 없다.
    //추상메서드(Abstract method)
    //Abstract method 메세드는 구현부({})가 없다.
    public void run();
}
 
cs

 

728x90