TIL

12 다형성

01 다형성

02 상속의 양면성

상속을 사용한 강의 평가

public class Lecture {
    private int pass; // 이수 여부 판단할 기준 점수
    private String title; // 강의 제목
    private List<Integer> scores = new ArrayList<>(); // 학생들의 성적

    public Lecture(String title, int pass, List<Integer> scores) {
        this.title = title;
        this.pass = pass;
        this.scores = scores;
    }

    public double average() {
        return scores.stream().mapToInt(Integer::intValue).average().orElse(0);
    }

    public String evaluate() {
        return String.format("Pass:%d Fail:%d", passCount(), failCount());
    }

    // ...
}
public class GradeLecture extends Lecture {
    private List<Grade> grades;

    public GradeLecture(String name, int pass, List<Grade> grades, List<Integer> scores) {
        super(name, pass, scores);
        this.grades = grades;
    }

    @Override
    public String evaluate() {
        return super.evaluate() + ", " + gradesStatistics();
    }

    private String gradesStatistics() {
        return grades.stream().map(grade -> format(grade)).collect(joining(" "));
    }

    private String format(Grade grade) {
        return String.format("%s:%d", grade.getName(), gradeCount(grade));
    }

    private long gradeCount(Grade grade) {
        return getScores().stream().filter(grade::include).count();
    }

    public double average(String gradeName) {
        return grades.stream()
                .filter(each -> each.isName(gradeName))
                .findFirst()
                .map(this::gradeAverage)
                .orElse(0d);
    }

    private double gradeAverage(Grade grade) {
        return getScores().stream()
                .filter(grade::include)
                .mapToInt(Integer::intValue)
                .average()
                .orElse(0);
    }
}

데이터 관점의 상속

행동 관점의 상속

03 업캐스팅과 동적 바인딩

같은 메시지, 다른 메서드

public class Professor {
    private String name;
    private Lecture lecture;

    public Professor(String name, Lecture lecture) {
        this.name = name;
        this.lecture = lecture;
    }

    public String compileStatistics() {
        return String.format("[%s] %s - Avg: %.1f", name,
                lecture.evaluate(), lecture.average());
    }
}
Professor professor = new Professor("다익스트라", 
                        new Lecture("알고리즘",
                            70,
                            List.of(81, 95, 75, 50, 45)));

String statistics = professor.compileStatistics();
// [다익스트라] Pass:3 Fail:2 - AVG: 69.2

Professor professor = new Professor("다익스트라", 
                        new GradeLecture("알고리즘",
                            70,
                            List.of(new Grade("A", 100, 95), ...),
                            List.of(81, 95, 75, 50, 45)));

String statistics = professor.compileStatistics();
// [다익스트라] Pass:3 Fail:2, A:1 B:1 C:1 D:1 F:1 - AVG: 69.2

업캐스팅

동적 바인딩

04 동적 메서드 탐색과 다형성

자동적인 메시지 위임

동적인 문맥

public class Lecture {
    public String stats() {
        return String.format("ㅅTitle: %s, Evaluation Method: %s", title, getEvaluationMethod());
    }

    public String getEvaluationMethod() {
        return "Pass or Fail";
    }
}
public class GradeLecture extends Lecture {
    @Override
    public String getEvaluationMethod() {
        return "Grade";
    }
}

이해할 수 없는 메시지

self 대 super

05 상속 대 위임

위임과 self 참조

프로토타입 기반의 객체지향 언어