개발 수업/JAVA

[Java] 다형성/필드의 다형성,매개 변수의 다형성

오늘 하루s 2023. 5. 18. 19:57
728x90
더보기

Day15-2. 230518

다형성(Polymorphism)

필드의 다형성

  • 다형성을 구현하는 기술적 방법

- 부모 타입으로 자동 변환

- 재정의된 메소드(오버라이딩)

 

Tire 클래스>

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
package chap0607;
 
public class Tire {
    //필드
    int price; //가격
    int maxRotation; //최대회전수
    int accmulatedRotation; //누적회전수
    String location;//타이어의 위치
    
    //생성자
       Tire(String location,int maxRotation){
        this.location=location;
        this.maxRotation=maxRotation;
    }
    
    //메서드
    boolean roll() {
        ++accmulatedRotation;
        if( accmulatedRotation<maxRotation ) {
            System.out.println(location+"Tire수명:"+
                    (maxRotation-accmulatedRotation)+"회");
            return true;
        }else {
            System.out.println(location+"Tire펑크!");
            return false;
        }
    }    
}
cs

 

Tire를 부품으로 가지는 클래스>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package chap0607;
 
public class Car {
    //필드
    Tire fL_Tire = new Tire("앞좌",6);
    Tire fR_Tire = new Tire("앞우",2);
    Tire bL_Tire = new Tire("뒤좌",3);
    Tire bR_Tire = new Tire("뒤우",4);
    
    //생성자
    //메서드
    int run(){
        System.out.println("자동차달려요-Car의 run()");
        if(fL_Tire.roll()==false) {    stop(); return 1;}
        if(fR_Tire.roll()==false) {    stop(); return 2;}
        if(bL_Tire.roll()==false) {stop(); return 3;}
        if(bR_Tire.roll()==false) {stop(); return 4;}
        return 0;  //No problem일 때
    }
    void stop(){
        System.out.println("자동차멈춥니다-Car의 stop()");
    }
}
cs

 

Tire의 자식 클래스 TireHankook>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package chap0607;
 
//p342 :TireHankook는 Tire를 상속받는하위클래스이다.
public class TireHankook extends Tire{
    //필드
    //생성자
    TireHankook(String location,int maxRotation){
        super(location,maxRotation);
    }
    
    //메서드
    @Override
    boolean roll() {
        ++accmulatedRotation;
        if( accmulatedRotation<maxRotation ) {
            System.out.println(location+"한국Tire수명:"+
                    (maxRotation-accmulatedRotation)+"회");
            return true;
        }else {
            System.out.println(location+"한국Tire펑크!");
            return false;
        }
    }
}
cs

 

Tire의 자식 클래스 Tirekumho>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package chap0607;
 
//p342 :Tire Hankook는 Tire를 상속받는하위클래스이다.
public class Tirekumho extends Tire{
    //필드
    //생성자
    Tirekumho(String location,int maxRotation){
        super(location,maxRotation);
    }
    
    //메서드
    @Override
    boolean roll() {
        ++accmulatedRotation;
        if( accmulatedRotation<maxRotation ) {
            System.out.println(location+"금호Tire수명:"+
                    (maxRotation-accmulatedRotation)+"회");
            return true;
        }else {
            System.out.println(location+"금호Tire펑크!");
            return false;
        }
    }    
}
cs

 

Car실행클래스>

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
package chap0607;
 
public class Car07_p343 {
 
    public static void main(String[] args) {
        Car07 car = new Car07();
        
        for(int i=1; i<=5; i++) {
            System.out.println(">>"+i+"번째 run()호출");
            int problemLoc = car.run();
            switch(problemLoc){
            case 1:
                System.out.println("앞왼쪽 Hankook타이어로 교체");
                car.fL_Tire = new TireHankook("앞왼쪽",15);
                break;
            case 2:
                System.out.println("앞R쪽 Hankook타이어로 교체");
                car.fR_Tire = new TireHankook("앞R쪽",13);
                break;
            case 3:
                System.out.println("뒤왼쪽 kumho타이어로 교체");
                car.bL_Tire = new Tirekumho("뒤왼쪽",14);
                break;
            case 4:
                System.out.println("뒤R쪽 kumho타이어로 교체");
                car.bR_Tire = new Tirekumho("뒤R쪽",17);
                break;
            }
            System.out.println("---------");
        }
    }
}
cs

 

더보기

* 실행 결과

 

>>1번째 run()호출
자동차달려요-Car의 run()
앞좌Tire수명:5회
앞우Tire수명:1회
뒤좌Tire수명:2회
뒤우Tire수명:3회
---------
>>2번째 run()호출
자동차달려요-Car의 run()
앞좌Tire수명:4회
앞우Tire펑크!
자동차멈춥니다-Car의 stop()
앞R쪽 Hankook타이어로 교체
---------
>>3번째 run()호출
자동차달려요-Car의 run()
앞좌Tire수명:3회
앞R쪽한국Tire수명:12회
뒤좌Tire수명:1회
뒤우Tire수명:2회
---------
>>4번째 run()호출
자동차달려요-Car의 run()
앞좌Tire수명:2회
앞R쪽한국Tire수명:11회
뒤좌Tire펑크!
자동차멈춥니다-Car의 stop()
뒤왼쪽 kumho타이어로 교체
---------
>>5번째 run()호출
자동차달려요-Car의 run()
앞좌Tire수명:1회
앞R쪽한국Tire수명:10회
뒤왼쪽금호Tire수명:13회
뒤우Tire수명:1회
---------

 

 

매개 변수의 다형성

- 자동 타입 변환은 필드의 값을 대입할 때에도 발생하지만, 주로 메소드를 호출할 때 많이 발생.

- 매개 변수의 타입과 동일한 매개값을 지정하는 것이 정석이지만,

- 매개값을 다양화하기 위해 매개 변수에 자식 객체를 지정 할 수 있음.

 

부모 클래스>

1
2
3
4
5
6
7
package chap0607;
 
class Vehicle{
    public void run() {
        System.out.println("Vehicle-run()메서드호출진입");
    }
}
cs

 

Vehicle을 이용하는 클래스>

1
2
3
4
5
6
7
package chap0607;
 
class Driver{
    void drive(Vehicle vehicle) {
        vehicle.run();
    }
}
cs

drive() 메소드에서 Vehicle타입의 매개값을 받아서 run()메소드 호출.

 

자식클래스 Bus>

1
2
3
4
5
6
7
8
package chap0607;
 
class Bus extends Vehicle{
    @Override
    public void run() {
        System.out.println("Bus-run()");
    }
}
cs

 

자식클래스 Taxi>

1
2
3
4
5
6
7
8
package chap0607;
 
class Taxi extends Vehicle{
    @Override
    public void run() {
        System.out.println("Taxi-run()");
    }
}
cs

 

실행클래스>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package chap0607;
 
public class Polymorphism {
    public static void main(String[] args) {
        Driver driver = new Driver();
        driver.drive(new Vehicle()); 
        
        Bus bus = new Bus();
        driver.drive(bus); //자동 타입 변환 : Vahicle vehicle = bus;
        
        Taxi taxi = new Taxi();
        driver.drive(taxi); //자동 타입 변환 :  Vahicle vehicle = taxi;
    }
}
cs
더보기

*실행 결과

 

Vehicle-run()메서드호출진입
Bus-run()
Taxi-run()

728x90