다형성(polymorphism)

장윤찬·2021년 11월 15일
0

dart language

목록 보기
3/12
post-thumbnail

goal : dart 언어의 다형성을 이해하자.

다형성이란?

상속받은 클래스의 기능을 확장하거나 변경하는 것을 가능하게 해준다. 이를 통해 코드의 재사용과 코드길이 감소가 되어 유지보수가 용이하도록 도와준다.

@override 재정의

다형성을 구축하는 방법은 아래와 같다.

class 자식클래스 extends 부모클래스{
  
  재정의할 부모클래스 메소드작성

다음상황을 가정하자.

class Car{
  
  int numberofseat=5;
  void drive(){
    print('wheels turn');
  }
  
} // 부모클래스

class SelfCar extends Car{} // 'Car' 클래스를 상속받은 자식클래스

'SelfCar' 클래스는 'Car' 클래스의 속성과 메소드를 그대로 상속받은 상태이다.

'SelfCar' 클래스의 'drive()' 기능을 다르게 정의해보자.

  • 'SelfCar'
    -새 속성
    String destination
    -생성자설정
    SelfCar(this.destination){} // 속성값초기화
    -drive()재정의
    print('go to $destination')
class SelfCar extends Car{
  
  String destination=;
  SelfCar(this.destination){
  }
  
  void drive(){
    super.drive(); // 부모클래스의 기능또한 그대로 구현하기
    print('go to the $destination');
  }
}

'SelfCar' 클래스가 상속받은 'drive()' 메소드가 설정한대로 재정의된것을 확인할 수 있다.

profile
Flutter 학습 일기

0개의 댓글