추상 기반 동작
Coddy의 Kotlin 개발자를 위한 Dart 코스 레슨. 48개 중 35번째.
Kotlin과 Dart의 추상 클래스는 공통 구현과 추상 메서드를 결합할 수 있습니다. 구체 메서드는 실제 객체의 특수화된 구현을 호출할 수 있습니다. 두 추상 클래스 모두 직접 생성할 수 없습니다.
추상 클래스는 직접 인스턴스화할 수 없습니다. 추상 요구 사항과 구체적인 공통 동작을 결합할 수 있습니다. 구체 메서드는 하위 클래스가 제공하는 특수화된 재정의 메서드를 호출할 수 있습니다.
Kotlin 전체 프로그램:
abstract class Shape{abstract fun name():String;fun label()="shape:"+name()};class Circle:Shape(){override fun name()="circle"}
fun main(){println(Circle().label())}
Dart 전체 프로그램:
abstract class Shape{String name();String label()=>'shape:'+name();}
class Circle extends Shape{String name()=>'circle';}
void main(){print(Circle().label());}챌린지
쉬움추상 클래스 Charge에 추상 메서드 cost(int units)와 동적 디스패치를 사용해 두 비용을 합산하는 구체 메서드 pair(int a,int b)를 구현하세요. FlatCharge(int fee)는 Charge를 상속합니다. 비용은 단위 수가 0이면 0이고, 그렇지 않으면 요금입니다. UnitCharge(int rate)는 Charge를 상속합니다. 비용은 요금과 단위 수의 곱입니다. 입력은 모드 flat 또는 unit, 금액, a와 b이며 모두 0 이상 100 이하의 정수입니다. 쌍의 비용을 출력하세요.
편집 가능한 파일에서 출력하지 마세요. 제공된 exercise.dart가 입력을 파싱하고 출력을 반환합니다. 잠긴 드라이버는 공개 API를 별도로 테스트하고 결과를 줄바꿈 하나와 함께 출력합니다.
코드는 Charge.dart, FlatCharge.dart, UnitCharge.dart, exercise.dart에 작성하세요. main.dart에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다.
직접 해보기
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Charge.dart';
import 'FlatCharge.dart';
import 'UnitCharge.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
final Charge a=FlatCharge(7),b=UnitCharge(3);check(a.cost(0)==0 && a.cost(2)==7 && a.pair(1,2)==14);check(b.cost(4)==12 && b.pair(2,3)==15);
stdout.writeln(solve(input));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Kotlin 개발자를 위한 Dart의 모든 레슨
직접 연습해 보세요: 온라인 Dart 컴파일러