본문 바로가기
STUDY/JAVA

다형성(Polymorphism)2

by NOTEEE 2018. 1. 22.

다형성

abstract class Calculator{
    int left, right;
    public void setOprands(int left, int right){
        this.left = left;
        this.right = right;
    } 
    int _sum() {
        return this.left + this.right;
    }
    public abstract void sum();  
    public abstract void avg();
    public void run(){
        sum();
        avg();
    }
}
class CalculatorDecoPlus extends Calculator {
    public void sum(){
        System.out.println("+ sum :"+_sum());
    }
    public void avg(){
        System.out.println("+ avg :"+(this.left+this.right)/2);
    }
class CalculatorDecoMinus extends Calculator {
    public void sum(){
        System.out.println("- sum :"+_sum());
    }
    public void avg(){
        System.out.println("- avg :"+(this.left+this.right)/2);
    }
public class Polymorphism3 {
    // 클래스 CalculatorDecoPlus를 Calculator화 시킴으로써 간략한 소스가 되었음.
    public static void execute(Calculator cal){
        System.out.println("실행결과");
        cal.run();
    }
    public static void main(String[] args) {
        // 클래스 CalculatorDecoPlus를 Calculator화 시킴.
        Calculator c1 = new CalculatorDecoPlus();
        c1.setOprands(1020);
        
        // 클래스 CalculatorDecoPlus를 Calculator화 시킴.
        Calculator c2 = new CalculatorDecoMinus();
        c2.setOprands(1020);
        
        // 만약 클래스 CalculatorDecoPlus를 Calculator화 시키지 않았다면 execute함수를 두번 선언했어야했다.
        execute(c1);
        execute(c2);
    }
}
cs


'STUDY > JAVA' 카테고리의 다른 글

인터페이스와 다형성2  (0) 2018.01.22
인터페이스와 다형성1  (0) 2018.01.22
다형성(Polymorphism)1  (0) 2018.01.22
Interface3  (0) 2018.01.22
Interface2  (0) 2018.01.22