상속과 다형성_java사전교육 22~25

두윤기·2022년 12월 22일

22. Inheritance & Polymorphism 1

  • 프로그램의 구조(객체 지향에 잘 맞게 프로그램을 구성)를 잘 잡으면, 유지 보수가 쉬워진다

> inheritance

  • 클래스를 정의할 때 이미 구현된 class를 inheritance(상속) 받아서 property나 method를 확장하는 class 구현
  • superclass(parent)
    • 상속하는 클래스, 상위클래스, base class
    • 상위클래스는 하위클래스보다 일반적인 의미
  • subclass(child)
    • 상속받는 클래스, 하위클래스, derived class
    • 하위클래스는 상위클래스보다 구체적인 의미
  • class inheritance syntax
class B extends A {

}

  • 단순 code 재사용을 위한 상속 X
    ex) Point, Circle -> has - a 관계

> inheritance를 활용한 고객관리 program

  • 고객의 정보를 활용하여 고객 맞춤 서비스 구현
  • 고객의 등급에 따라 차별화된 할인율과 point 지급
  • 등급에 따른 class를 구현하는 것이 아닌 일반적인 class를 먼저 구현하고, 그보다 기능이 많은 class는 inheritance를 활용하여 구현
  • Customer class property
  • Customer class method
    • Customer()
      Default: customerGrade = "SILVER", bonusRatio = 1%
    • calcPrice(int price)
      제품에 대해 지불해야 하는 금액을 계산하여 반환
      할인되지 않는 경우 가격을 그대로 반환
      가격에 대해 bonusRatio를 적용하여 bonusPoint 적립
    • showCustomerInfo()
      고객의 정보(customerName, customerGrade, bonusPoint) 출력

> new customerGrade arise

  • 단골고객 혜택 필요
  • 우수고객 관리, 혜택
  • customerGrade = VIP, discountRate = 10%, bonusRatio = 5%, 전문 상담원 배정


23. Inheritance & Polymorphism 2

> access modifier

> inheritance class 생성 과정

  • subclass가 생성될 때, superclass가 먼저 생성됨
  • superclass의 constructor가 호출되고, subclass의 constructor가 호출 됨
  • subclass의 constructor에서는 무조건 superclass의 constructor가 호출되어야 함
  • 아무것도 없는 경우 compiler는 superclass default constructor를 호출하기 위한 super()를 code에 넣어줌
  • super() 호출되는 constructor는 superclass의 default constructor임
  • 만약 superclass의 default constructor가 없는 경우 (매개변수가 있는 constructor만 존재하는 경우) subclass는 명시적으로 superclass를 호출해야함

> inheritance 에서의 메모리 상태

  • superclass의 instance가 먼저 생성되고, subclass의 instance가 생성됨
  • superclass instance의 property 중 private이 있다면, 생성은 됐지만 access가 안됨(getter, setter)

> super

  • this가 자기 자신의 instance 주소를 가지는 것처럼
  • super는 subclass가 superclass에 대한 주소를 가지게 됨
  • subclass가 superclass에 access할 때 사용할 수 있음

> Upcating (superclass로의 implicit type conversion)

  • superclass 형으로 변수를 선언하고 subclass instance를 생성할 수 있음
  • subclass는 superclass type을 내포하고 있으므로 superclass가 implicit type conversion이 가능함

> 형 변환에서의 메모리

  • Customer vc = new VIPCustomer();에서 vc가 가리키는 것은?
  • VIPCustomer() constructor의 호출로 instance는 모두 생성되었지만, type이 Customer이므로 access할 수 있는 변수나 method는 Customer의 변수와 method임

> method overriding

  • superclass에 정의된 method 중 subclass와 기능이 맞지 않거나 추가 기능이 필요한 경우 같은 이름과 매개변수로 subclass에서 재정의
  • VIPCustomer class의 calcPrice() method 재정의
    보너스 포인트 적립하고, 할인률을 적용한 가격 반환
public int calcPrice(int price){
	bonusPoint += price * bonusRatio;
    return price - (int)(price * saleRatio);
}

#### annotation * 주석처럼 프로그램에 영향을 미치지 않으면서 유용한 정보 제공 * compiler가 parameter를 검토하게 지시 * ex) @Override ## 24. Overriding & Polymorphism ### > upcating과 overriding된 method 호출 ``` Customer vc = new VIPCustomer(); vc.calcPrice(10000); ``` 위 코드에서 calcPrice() method는 어느 method가 호출될까? ![](https://velog.velcdn.com/images/dooshine95/post/db8b69fc-52ca-46ea-9530-6272a6d6ed17/image.png)

> virtual method (가상 메서드)

  • 프로그램에서 어떤 객체의 variable이나 method의 참조는 그 type에 따라 이루어짐. virtual method의 경우는 type과 상관없이 실제 생성된 instance의 method가 호출되는 원리
Customer vc = new VIPCustomer();
vc.calcPrice(10000);
  • vc의 type은 Customer지만, 실제 생성된 instance인 VIPCustomer class의 calcPrice() method가 호출됨

> Polymorphism (다형성)

  • ? 하나의 code가 여러가지 자료형으로 구현되어 실행되는 것 ?
  • 정보은닉, inheritance와 더불어 OOP의 가장 큰 특징 중 하나
  • OOP의 유연성, 재활용성, 유지보수성에 기본이 되는 특징

> Polymorphism 구현

  • 하나의 class를 inheritance한 여러 class가 있는 경우 각 class마다 같은 이름의 서로 다른 method를 재정의
  • superclass type으로 선언된 하나의 variable이 여러 instance에 대입되어 다양한 구현이 실행

> Polymorphism 활용

  • 일반 고객과 VIP 고객의 중간 등급의 고객 생성
  • 5명의 고객을 ArrayList에 생성하여 저장한 다음
  • 각 고객이 물건을 샀을 때의 price와 bonusPoint 계산

> Inheritance 활용

  • 여러 class를 생성하지 않고, 하나의 class에 공통적인 요소를 모으고, 나머지 class는 이를 inheritance한 다음 각각 필요한 property와 method를 구현
  • 하나의 class에 여러 property를 한꺼번에 구현하는 경우, 많은 code 내에 많은 if문이 생길 수 있음

IS-A Relationship (IS-A 관계)

  • general(일반적인) 개념과 specific(구체적인) 개념과의 관계
  • superclass, subclass
  • 단순히 코드를 재사용하는 목적으로 사용 X

HAS-A Relationship (composition)

  • 한 class가 다른 class를 소유한 관계
  • 코드 재사용의 한 방법
  • Student가 Subject를 포함한 관계
class Student {
	Subject majorSubject;
}

25. Polymorphism 활용과 downcasting

> polymorphism 활용하기

  • 일반 고객과 VIP 고객의 중간 등급의 고객을 생성
  • 5명의 고객을 ArrayList에 생성하여 저장한 다음 각 고객이 물건을 샀을 때 가격과 보너스 포인트 계산

> downcasting - instanceof

  • subclass가 superclass로 형 변환 되는 것은 묵시적으로 이루어짐
  • 다시 원래 data type인 subclass로 type conversion하려면 explicit으로 downcasting 해야함
  • 이 때, 원래 instance의 type을 체크하는 keyword가 instanceof임

? downcasting할 때,

Human human;
if(animal instanceof Human) {
	human = (Human)animal;
}
human.readBook();

이렇게 나누면 왜 error가 뜰까?

profile
programmerD

0개의 댓글