Dart언어 추상화 클래스

밥이·2022년 5월 10일
0

Dart언어

목록 보기
4/4
import 'inheritance/circle.dart';
import 'inheritance/rectangle.dart';
import 'inheritance/shape.dart';

void main() {

  // Shape사용하기
  Circle circle = Circle(3);
  Rectangle rectangle = Rectangle(5, 10.3);

  printArea(circle);
  printArea(rectangle);
  // printArea(Shape());
  // abstract class는 인스턴스화를 못함, 자식클래스로 인스턴스화를 해야함
}

void printArea(Shape shape) {
  print('면적 : ${shape.getArea()}');
}

shape.dart

// 추상화클래스(abstract class)
// abstract class는 인스턴스화를 못함, 자식클래스로 인스턴스화를 해야함
// circle와 rectangle를 인스턴스화 시켜야함

abstract class Shape {
  double getArea();
}

// 정리
// abstract class는 다음과 같이 구현체(body)가 없는 메소드를 정의할 수 있고
// 구현체(body)가 없기때문에 상속받은 circle와 rectangle 들은 override(재정의)을 강제적으로 부여함
// abstract class는 인스턴스화를 못한다.

// class Shape {
//   double getArea() {
//     return 0;
//   }
// }

circle.dart

import 'shape.dart';

// 반지름 너비 구하는 함수 만들기
class Circle extends Shape {
  Circle(this.redius);

  double redius;

// 추상화클래스로 되어있을때, 구현체(body)가 없다면
// 무조건 필수적으로 구현체(body)를 작성하게끔 강제성을 부여함
  @override
  double getArea() {
    return redius * redius * 3.14;
  }
}
// extends로 작성했을때는 body부분이 없는것만 즉, 메소드 구현체가 없는것만 필수적으로 재정의
// 나머지는 선택사항
// 
// implements로 작성했을때는 작성된 변수와 함수 모두를
// 재정의 해야한다.

// class Circle implements Shape {
//   Circle(this.redius);

//   double redius;

//   @override
//   double getArea() {
//     return redius * redius * 3.14;
//   }
// }

rectangle.dart

import 'shape.dart';

// 직사각형 너비 구하기
class Rectangle extends Shape {
  Rectangle(this.width, this.height);

  double width;
  double height;

// 추상화클래스로 되어있을때, 구현체가 없다면
// 무조건 필수적으로 구현체(body)를 작성하게끔 강제성을 부여함
  @override
  double getArea() {
    return width * height;
  }
}

0개의 댓글