티스토리 뷰

반응형

31. 다운 캐스팅과 instanceof

| 하위 클래스로 형변환, 다운 캐스팅

묵시적으로 상위 클래스 형변환된 인스턴스가 원래 자료형( 하위 클래스)로 변환되어야할때 다운 캐스팅이라고 함.

하위 클래스로의 형변환은 명시적으로 돼야함.

Customer vc = new VIPCustomer(); // 묵시적
VIPCustomer vCustomer = (VIPCustomer) vc; // 명시적

 

 

package polymorphism;

import java.util.ArrayList;

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

	}
}

class Human extends Animal {
	public void move() {
		System.out.println("사람이 두 발로 걷습니다.");
	}

	public void readBooks() {
		System.out.println("사람이 책을 읽습니다.");
	}
}

class Tiger extends Animal {
	public void move() {
		System.out.println("호랑이가 네 발로 뜁니다.");

	}

	public void hunting() {
		System.out.println("호랑이가 사냥을 합니다.");

	}
}

class Eagle extends Animal {
	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();

		// AnimalTest test = new AnimalTest();
		// test.moveAnimal(hAnimal);
		// test.moveAnimal(tAnimal);
		// test.moveAnimal(eAnimal);
		/*
		 * 사람이 두 발로 걷습니다. 호랑이가 네 발로 뜁니다. 독수리가 하늘을 날아갑니다.
		 * 
		 */
		// Human human = (Human) hAnimal;
		// 문제점: Eagle human = (Eagle) hAnimal; 에러!!! 에러에서 안잡히는데, 후에 에러로 컴파일 fail
		// 해결책: instanceof 사용 : 얘가 정말 이 타입의 인스턴스 였는가? => 안정성 증가!!!!
		// if (hAnimal instanceof Human) {
		// Human human = (Human) hAnimal;
		// human.readBooks();
		// }

		ArrayList<Animal> animalList = new ArrayList<Animal>();
		animalList.add(hAnimal);
		animalList.add(tAnimal);
		animalList.add(eAnimal);

		AnimalTest test = new AnimalTest();
		test.testingDownCasting(animalList);
		/*
		 * 사람이 책을 읽습니다.
			호랑이가 사냥을 합니다.
			독수리 전광속화!
			=================

		 */

		System.out.println("=================");
		// for (Animal animal : animalList) {
		// animal.move();
		// }
	}

	public void testingDownCasting(ArrayList<Animal> list) {
		for (int i = 0; i < list.size(); i++) {
			Animal animal = list.get(i);
			if (animal instanceof Human) {
				Human human = (Human) animal;
				human.readBooks();

			} else if (animal instanceof Tiger) {
				Tiger tiger = (Tiger) animal;
				tiger.hunting();

			} else if (animal instanceof Eagle) {
				Eagle eagle = (Eagle) animal;
				eagle.flying();
			} else {
				System.out.println("error");
			}
		}
	}

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

}

32. 코딩해 보세요

 

 

package polymorphism;

public class Customer {
	private static int totalCustomerNum = 0;
	protected int customerID;
	protected String customerName;
	protected String customerGrade; // 자식이 쓸수 있게 p rotected
	int bonusPoint;
	double bonusRatio;

	public Customer(String customerName) {
		totalCustomerNum++;
		customerID = totalCustomerNum;
		this.customerName = customerName;
		customerGrade = "SILVER";
		bonusRatio = 0.01;
		// System.out.println("customer 생성자 호출");
	}

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

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

	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;
	}

}
package polymorphism;

public class GoldCustomer extends Customer {

	double salesRatio;

	public GoldCustomer(String customerName) {
		super( customerName);
		customerGrade = "GOLD";
		bonusRatio = 0.02;
		salesRatio = 0.1;

	}

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

}

 

 

 

 

package polymorphism;

public class VIPCustomer extends Customer {
	private static int agentTotalNum = 1000;
	private int agentID;
	double salesRatio;

	public VIPCustomer( String customerName) {
		super(customerName);
		// TODO Auto-generated constructor stub
		customerGrade = "VIP";
		bonusRatio = 0.05;
		salesRatio = 0.1;
		agentTotalNum += 1;
		this.agentID = agentTotalNum;
		// System.out.println("VIPcustomer int, name 생성자 호출");
	}

	@Override
	public int calcPrice(int price) {
		// TODO Auto-generated method stub
		return (int) (super.calcPrice(price) * (1 - this.salesRatio));
	}

	@Override
	public String showCustomerInfo() {
		// TODO Auto-generated method stub
		return super.showCustomerInfo()+"담당 상담원 번호는 "+this.agentID+"입니다.";
	}


}

 

 

 

 

 

 

 

 

바 인강이 듣고 싶다면 => https://bit.ly/3ilMbIO

반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/02   »
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
글 보관함