상속과 Super
Coddy의 C 개발자를 위한 Java 코스 레슨. 48개 중 39번째.
C에는 내장 클래스 상속이나 가상 메서드가 없습니다. 콜백과 명시적인 상태를 사용해 디스패치를 수동으로 모델링할 수 있습니다. Java의 인스턴스 메서드 오버라이딩은 런타임 객체 유형에 따라 디스패치되며, super 호출은 슈퍼클래스 구현을 호출합니다. Java 클래스는 하나의 클래스를 확장하고 여러 인터페이스를 구현할 수 있습니다. 정적 메서드는 가상 인스턴스 오버라이드가 아닙니다.
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdarg.h>
#include <errno.h>
#include <limits.h>
#include <ctype.h>
struct Pass {int base;int (*cost)(const struct Pass *);};
static int discounted(const struct Pass *pass) { return pass->base-5; }
int main(void) {
struct Pass pass={12,discounted}; printf("%d\n",pass.cost(&pass));
return 0;
}
Java
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Example {
static class Pass {int cost(){return 12;}}static class Discount extends Pass {@Override int cost(){return super.cost()-5;}}
public static void main(String[] args) {
Pass p=new Discount();System.out.println(p.cost());
}
}
예제는 각 언어의 동작을 따로 보여 주며 서로 다른 값을 사용할 수도 있습니다. 각 예제를 독립적으로 추적하세요. 예상 출력이 서로 같다고 가정하지 마세요. Java 과제에서는 편집 가능한 클래스를 통해 같은 개념을 새로운 입력에 적용합니다.
챌린지
쉬움입력은 기본 가격과 할인 금액 순이며, 둘 다 0 이상이고 할인 금액은 가격보다 클 수 없습니다. Pass(int)와 cost()를 구현하고, Pass를 확장하며 상속된 가격에서 할인 금액을 빼서 cost를 재정의하는 DiscountPass(int,int)를 구현하세요. 두 비용을 모두 반환하세요.
Exercise.solve(List<String> input)에서 끝에 줄바꿈이 없는 정확한 결과 텍스트를 반환하세요. 화면에 표시되는 잠긴 Main.java는 모든 입력 줄을 읽고 반환된 텍스트를 끝에 줄바꿈 하나와 함께 출력합니다. 편집 가능한 메서드 안에서 출력하지 마세요. 달리 명시되지 않는 한 모든 정수와 산술 결과는 Java int 범위에 들어갑니다.
편집 가능한 파일: Pass.java, DiscountPass.java, Exercise.java, Text.java. Text.java에는 재사용 가능한 구문 분석 및 형식 지정 도우미가 있습니다. 모든 파일은 이름 없는 패키지에 있으며 함께 컴파일됩니다. Main.java만이 진입점이며 편집할 수 없습니다.
화면에 표시되는 잠긴 드라이버는 입력 사례를 실행하기 전에 별도의 새 객체를 사용해 필수 클래스 API도 호출합니다. 해당 API를 구현하세요. 최종 출력만 하드코딩하는 것으로는 충분하지 않습니다.
직접 해보기
import java.io.*;
import java.util.*;
public class Main {
private static void check(boolean condition) {
if (!condition) throw new AssertionError("Required public API behavior failed");
}
public static void main(String[] args) throws Exception {
List<String> input = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = reader.readLine()) != null) input.add(line);
Pass p=new DiscountPass(12,5);check(p.cost()==7&&new Pass(8).cost()==8);
System.out.println(Exercise.solve(input));
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C 개발자를 위한 Java의 모든 레슨
직접 연습해 보세요: 온라인 Java 컴파일러