Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

WON.dev

chapter16 : polymorphism 본문

JAVA

chapter16 : polymorphism

GAWON 2023. 5. 16. 18:33
1.1 다형성 (Polymorphism)
 - 상속관계는 부모와 자식으로 구성되어 있다.
 - 부모클래스의 객체(인스턴스) = 참조변수(레퍼런스)는 자식클래스의 객체를 저장 할 수 있다. 
    (Upcasting) ★
		( → 한가지 객체가 다른 타입의 객체가 될 수 있다.)

1.2 업캐스팅 (Upcasting)
 - 부모클래스의 참조변수에 자식클래스의 객체를 저장할 수 있다.
 - 사용 형식
	ex)부모클래스 참조변수  = new 자식클래스();
 - 부모클래스에 존재하지않는 멤버는 호출 할 수 없다.(한계점)
 - 부모클래스에는 없고, 자식클래스만 가지고있는 멤버는 호출 할 수 없다.(한계점)

1.3 다운캐스팅 (Downcasting)
 - 부모클래스의 참조변수에 저장한 자식클래스의 타입은 "부모클래스"이다.
 - 이와 같은형태의 자식클래스를 "자식클래스"타입으로 변경하는 것이 다운캐스팅이다.
 - 사용 형식
 	ex) 부모클래스 참조변수  = new 자식클래스();				→ 업캐스팅
		자식클래스 참조변수2 = (자식클래스)참조변수;			→ 다운캐스팅
 - 강제 형 변환으로 진행되기 때문에 잘못된 형 변환이 발생 할 수 있다.
		이를 방지하기 위해서 참조변수의 타입을 바꾸기 전에 확인하는 instanceof 연산자를 활용한다.★
		(부모클래스에는 없지만 자식클래스에만 있는 멤버를 사용하려고 다운캐스팅을 이용한다!)
Q1.Test01.java

Employee 클래스			필드 : String name, String dept
						메소드 : Constructor, int pay(), void output()
SalaryWorker 클래스		필드 : int salary
						메소드 : Constructor, int pay(), void output()
SalesWorker 클래스		필드 : int salesVolume,
							double salesIncentive --> 인센티브 비율(1000이상 10%, 500이상 5% 나머지 1%)
						메소드 : Constructor, int pay(), void output(),
								 int salesPay(),
								 void setSalesVolume(salesVolume),
								 void setSalesIncentive(salesIncentive)
PartTimeWorker 클래스	필드 : int workTime, int payPerHour
						메소드 : Constructor, int pay(), void output()
★
필드는 전부 private
SalaryWorker extends Employee
SalesWorker extends SalaryWorker
PartTimeWorker extends Employee



package org.joonzis.test;

class Employee{
	private String name;
	private String dept;
	
	public Employee() {}
	public Employee(String name, String dept) {
		this.name = name;
		this.dept = dept;
	}
	// pay() 메소드를 오버라이드 해서 사용하기 위해 
	// 굳이 부모 클래스에 넣어준 방식. 실제로는 의미가 없는 메소드
	// 나중에 추상 메소드를 배우자
	public int pay() {	
		return 0;
	}
	public void output() {
		System.out.println("이름 : " + name);
		System.out.println("부서 : " + dept);
	}
}
class SalaryWorker extends Employee{
	private int salary;
	
	public SalaryWorker() {}
	public SalaryWorker(String name, String dept, int salary) {
		super(name, dept);
		this.salary = salary;
	}
	@Override
	public int pay() {
		return salary;
	}
	@Override
	public void output() {
		super.output();
		System.out.println("기본급 : " + salary);
	}
}
class SalesWorker extends SalaryWorker{
	private int salesVolume;			// 판매량
	private double salesIncentive;		// 인센티브 비율
	
	public SalesWorker() {}
	public SalesWorker(String name, String dept, int salary) {
		super(name, dept, salary);
	}
	public void setSalesVolume(int salesVolume) {
		this.salesVolume = salesVolume;
		
		if(salesVolume >= 1000) {
			setSalesIncentive(0.1);
		}else if(salesVolume >= 500) {
			setSalesIncentive(0.05);
		}else {
			setSalesIncentive(0.01);
		}
	}
	public void setSalesIncentive(double salesIncentive) {
		this.salesIncentive = salesIncentive;
	}
	int salesPay() {
		return (int)(super.pay() * salesIncentive);
	}
	@Override
	public int pay() {
		return super.pay() + salesPay();
	}
	@Override
	public void output() {
		super.output();
		System.out.println("판매 수당 : " + salesPay());
		System.out.println("급여 : " + this.pay());
	}
}
class PartTimeWorker extends Employee{
	private int workTime, payPerHour;

	public PartTimeWorker() {}
	public PartTimeWorker(String name, String dept, int workTime, int payPerHour) {
		super(name, dept);
		this.workTime = workTime;
		this.payPerHour = payPerHour;
	}
	@Override
	public int pay() {
		return workTime * payPerHour;
	}
	@Override
	public void output() {
		super.output();
		System.out.println("급여 : " + this.pay());
	}
}
public class Test01 {
	public static void main(String[] args) {
		
//		Employee[] members = new Employee[3];
//		members[0] = new SalaryWorker("김씨", "관리자", 200);
//		members[1] = new SalesWorker("김씨", "관리자", 300);
//		members[2] = new PartTimeWorker("이씨", "영업부", 200, 2);
		
		Employee e1 = new SalaryWorker("김씨", "관리자", 200);
		e1.output();
		
		System.out.println("-------------");
		
		Employee e2 = new SalesWorker("김씨", "관리자", 300);
		if(e2 instanceof SalesWorker) {
			((SalesWorker)e2).setSalesVolume(1000);
		}
		e2.output();
		
		System.out.println("-------------");
		Employee e3 = new PartTimeWorker("이씨", "영업부", 200, 2);
		e3.output();
		
		
	}
}

Q2. Test02.java

Product 클래스			필드 : String model, int price
						메소드 : Constructor, getters
Tv 클래스					필드 : X
						메소드 : Constructor
Computer 클래스			필드 : X
						메소드 : Constructor
Customer				필드 : int money, int startMoney, Product[] cart, int numOfProduct
						메소드 : Constructor, buy(Product), output
★
필드는 전부 private
Tv extends Product
Computer extends Product
buy() -> 상품 구매(소지 금액보다 구매 금액이 큰 경우 예외처리)/구매한 만큼 금액 차감/카트에 상품 추가
output() -> 구매상품, 금액/처음 소지 금액/총 구매 금액/남은 금액 출력

== 2명의 Customer가 각각 Tv, Computer를 구매

package org.joonzis.test;

class Product{
	private String model;
	private int price;
	public Product(String model, int price) {
		this.model = model;
		this.price = price;
	}
	public String getModel() {
		return model;
	}
	public int getPrice() {
		return price;
	}
}
class Tv extends Product{
	public Tv(String model, int price) {
		super(model, price);
	}
}
class Computer extends Product{
	public Computer(String model, int price) {
		super(model, price);
	}
}
class Customer{
	private int money;							// 체크 카드 개념
	private int startMoney;						// 초기 금액
	private int numOfProduct;					// 인덱스
	private Product[] cart = new Product[10];	// 객체 생성 시 선언
	
	public Customer(int money) {
		this.startMoney = money;
		this.money = money;
	}
	public void buy(Product product) {
		// 현재 내 금액보다 구매 금액이 더 크면 메소드 탈출
		if(money < product.getPrice()) {
			System.out.println("소지 금액이 부족합니다.");
			return;
		}
		
		money = money - product.getPrice(); // 소지 금액에서 물건 금액 차감
	 	cart[numOfProduct] = product; 		// 물건 리스트를 배열에 저장
	 	numOfProduct++;
	}
	public void output() {
		int total = 0;
		// 구매 상품 : 모델, 가격
		for(int i=0; i<numOfProduct; i++) {
			System.out.println("구매 상품 : " + cart[i].getModel() + ", " + cart[i].getPrice());
			total += cart[i].getPrice();
		}
		
		// 처음 소지 금액
		System.out.println("처음 소지 금액 : " + startMoney);
		// 총 구매 금액
		System.out.println("총 구매 금액 : " + total);
		// 남은 금액
		System.out.println("남은 금액 : " + money);
	}
}
public class Test02 {
	public static void main(String[] args) {
		Customer customer1 = new Customer(1000);
		
		customer1.buy(new Tv("삼성 TV", 200));
		customer1.buy(new Computer("삼성 Computer", 150));
		customer1.output();
		
		
	}
}

'JAVA' 카테고리의 다른 글

chapter18 : interface  (0) 2023.05.16
chapter17 : abstract  (0) 2023.05.16
chapter15 : access_modifier  (0) 2023.05.16
chapter14 : package  (0) 2023.05.16
chapter13 : inheritance_annotation  (0) 2023.05.16