ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Java (5) - 상속
    웹개발/Java 2021. 2. 5. 17:23

    * 상속

    · 어떤 객체가 있을 때 그 객체의 필드(변수)와 메소드를 다른 객체가 물려받을 수 있는 기능

     

    - 아래와 같은 경우에 속한다면 객체에 메소드를 추가하는 것이 어려움 

    1. 객체를 자신이 만들지 않은 경우 소스를 변경할 수 없음

    2. 객체가 다양한 곳에서 활용되고 있는 경우 메소드를 추가하면 다른 곳에서는 불필요한 기능이 포함될 수 있음

     

    · 기존의 객체를 그대로 유지하면서 어떤 기능을 추가하는 방법 -> 상속

    즉, 기존의 객체를 수정하지 않으면서 새로운 객체가 기존의 객체를 기반으로 만들어지게 되는 것

    · 기존의 객체는 기능을 물려준다는 의미에서 부모 객체가 되고 새로운 객체는 기존 객체의 기능을 물려받는다는 의미에서 자식 객체가 됨

    · 부모 클래스와 자식 클래스의 관계를 상위(super) 클래스와 하위(sub) 클래스라고 표현하기도 함

    · 또한 기초 클래스(base class), 유도 클래스(derived class)라고도 부름

     

    package org.opentutorials.javatutorials.Inheritance.example1;
     
    class Calculator {
        int left, right;
     
        public void setOprands(int left, int right) {
            this.left = left;
            this.right = right;
        }
     
        public void sum() {
            System.out.println(this.left + this.right);
        }
     
        public void avg() {
            System.out.println((this.left + this.right) / 2);
        }
    }
     
    class SubstractionableCalculator extends Calculator {
        public void substract() {
            System.out.println(this.left - this.right);
        }
    }
     
    public class CalculatorDemo1 {
     
        public static void main(String[] args) {
     
            SubstractionableCalculator c1 = new SubstractionableCalculator();
            c1.setOprands(10, 20);
            c1.sum();
            c1.avg();
            c1.substract();
        }
     
    }

     

    · 클래스 다이어그램

    package org.opentutorials.javatutorials.Inheritance.example1;
     
    class MultiplicationableCalculator extends Calculator {
        public void multiplication() {
            System.out.println(this.left * this.right);
        }
    }
     
    public class CalculatorDemo2 {
     
        public static void main(String[] args) {
     
            MultiplicationableCalculator c1 = new MultiplicationableCalculator();
            c1.setOprands(10, 20);
            c1.sum();
            c1.avg();
            c1.multiplication();
        }
     
    }

     

    · 상속 받은 클래스를 다시 상속 가능

    package org.opentutorials.javatutorials.Inheritance.example1;
     
    class DivisionableCalculator extends MultiplicationableCalculator {
        public void division() {
            System.out.println(this.left / this.right);
        }
    }
     
    public class CalculatorDemo3 {
     
        public static void main(String[] args) {
     
            DivisionableCalculator c1 = new DivisionableCalculator();
            c1.setOprands(10, 20);
            c1.sum();
            c1.avg();
            c1.multiplication();
            c1.division();
        }
     
    }

     

    '웹개발 > Java' 카테고리의 다른 글

    Java (4) - 생성자  (0) 2021.02.05
    Java (3) - 클래스, 인스턴스  (0) 2021.02.03
    Java (2) - 배열  (0) 2021.02.01
    Java (1) - 설치와 실행  (0) 2021.02.01

    댓글

Designed by Tistory.