본문 바로가기
카테고리 없음

Java & SpringBoot로 시작하는 웹 프로그래밍 : 자바 인강 [3주차]

by 소윤:) 2022. 7. 5.
반응형
객체 지향 핵심

1. 상속

새로운 클래스를 정의할 때 이미 구현된 클래스를 상속 받아 속성이나 기능을 확장하여 클래스를 구현

이미 구현된 클래스보다 더 구체적인 기능을 가진 클래스를 구현해야 할때 기존 클래스를 상속

class 자식클래스 extends 부모클래스{
   //필드
   //생성자
   //메소드
}


상속하는 클래스 : 상위클래스, parent class, base class, super class
상속받는 클래스 : 하위 클래스, child class, derived class, subclass

2. 상속을 활용한 멤버십 클래스 구현하기

회사에서 고객 정보를 활용한 맞춤 서비스를 하기 위해 일반고객(Customer)과 우수고객(VIPCustomer)에 따른 서비스를 제공하고자 함
물품을 구매 할때 적용되는 할인율과 적립되는 보너스 포인트의 비율이 다름 

package ch02;

public class Customer {
	protected int customerID;
	protected String customerName;
	protected String customerGrade;
	int bonusPoint;
	double bonusRatio;
	
	public Customer() {
		customerGrade = "SILVER";
		bonusRatio = 0.01;

		System.out.println("Customer() call");
	}
	 
	public Customer(int customerID, String customerName) {
		this.customerID = customerID;
		this.customerName = customerName;

		customerGrade = "SILVER";
		bonusRatio = 0.01;
	}

	public int calcPrice(int price) {
		bonusPoint += price * bonusRatio;
		return price;
	}

	public int getCustomerID() {
		return customerID;
	}

	public void setCustomerID(int customerID) {
		this.customerID = customerID;
	}

	public String getCustomerName() {
		return customerName;
	}

	public void setCustomerName(String customerName) {
		this.customerName = customerName;
	}

	public String getCustomerGrade() {
		return customerGrade;
	}

	public void setCustomerGrade(String customerGrade) {
		this.customerGrade = customerGrade;
	}

	public String showCustomerInfo() {
		return customerName + "님의 등급은 " + customerGrade + "이며, 보너스포인트는 " + bonusPoint + "입니다.";
	}
}

* 외부클래스는 접근 할 수 없지만, 하위클래스는 접근가능하도록 protected 접근제어자 사용

* 이미 Customer에 구현된 내용이 중복되므로 확장하여 구현(상속)

package ch02;

public class VIPCustomer extends Customer {

	String agentID;
	double salesRatio;

	public VIPCustomer(int customerID, String customerName) {
		super(customerID, customerName);

		customerGrade="VIP";
		bonusRatio=0.05;
		salesRatio=0.1;

		System.out.println("VIPCustomer() call");
	}

	public String getAgentID() {
		return agentID;
	}
}

 

3. 상속에서 클래스 생성 과정

하위 클래스를 생성하면 상위 클래스가 먼저 생성

클래스를 상속 받은 경우 하위 클래스의 생성자에서는 반드시 상위 클래스의 생성자를 호출

super는 생성된 상위 클래스 인스턴스의 참조 값을 가지므로 super를 이용하여 상위 클래스의 메서드나 멤버 변수에 접근할 수 있음

 

4. 메서드 재정의하기(오버라이딩)

상위 클래스에 정의된 메서드의 구현 내용이 하위 클래스에서 구현할 내용과 맞지 않는 경우 하위 클래스에서 동일한 이름의 메서드를 재정의

  • 메서드 호출 과정
  1. 메서드의 이름은 주소값을 나타냄
  2. 메서드는 명령어의 set 이고 프로그램이 로드되면 메서드 영역(코드 영역)에 명령어 set이 위치
  3. 해당 메서드가 호출 되면 명령어 set 이 있는 주소를 찾아 명령어 실행
  4. 이때 메서드에서 사용하는 변수들은 스택 메모리에 위치
  5. 따라서 다른 인스턴스라도 같은 메서드의 코드는 같으므로 같은 메서드 호출
  6. 인스턴스가 생성되면 변수는 힙 메모리에 따로 생성되지만, 메서드 명령어 set은 처음 한번만 로드
@Override
	public int calcPrice(int price)	 {

		bonusPoint+=price*bonusPoint;
		price-=(int)(price*salesRatio);
		return super.calcPrice(price);
	}
애노테이션(주석) 설명
@Override 재정의된 메서드 (선언부가 기존의 메서드와 다른 경우 에러)
@Fuctionallnterface 함수형 인터페이스
@Deprecated 이후 버전에서 사용되지 않을 수 있는 변수, 메서드에 사용
@SuppressWarnings 특정 경고가 나타나지 않도록 함

5. 다형성

하나의 코드가 여러 자료형으로 구현되어 실행되는 것으로 같은 코드에서 여러 다른 실행결과가 나옴

정보은닉, 상속과 더불어 객체지향 프로그래밍의 가장 큰 특징

상속과 메서드 재정의를 활용하여 확장성 있는 프로그램을 만들 수 있음

상위 클래스에서는 공통적인 부분을 제공하고 하위 클래스에서는 각 클래스에 맞는 기능 구현

여러 클래스를 하나의 타입(상위 클래스)으로 핸들링 할 수 있음

package ch06;

import java.util.ArrayList;

class Animal{
	
	public void move() {
		System.out.println("동물이 움직입니다.");
	}
}

class Human extends Animal{

	@Override
	public void move() {
		System.out.println("사람이 두 발로 걷습니다.");
	}
	
	public void readBook(){
		System.out.println("사람이 책을 읽습니다.");
	}
}

class Tiger extends Animal{

	@Override
	public void move() {
		System.out.println("호랑이가 네 발로 뜁니다.");
	}
    
	public void hunting(){
		System.out.println("호랑이가 사냥을 합니다.");
	}
}

class Eagle extends Animal{

	@Override
	public void move() {
		System.out.println("독수리가 하늘을 날아다닙니다.");
	}
	
	public void flying(){
		System.out.println("독수리가 양 날개를 쭉 펴고 날아다닙니다.");
	}
}

public class AnimalTest {

	public static void main(String[] args) {

		Animal hAnimal = new Human();
		Animal tAnimal = new Tiger();
		Animal eAnimal = new Eagle();
		
		ArrayList<Animal> animalList=new ArrayList<>();
		animalList.add(hAnimal);
		animalList.add(tAnimal);
		animalList.add(eAnimal);
	
		for(Animal animal:animalList) {
			animal.move();
		}
	}

	public void moveAnimal(Animal animal) {
		animal.move(); 
	}
}
반응형