up casting, down casting, instanceof

김재원·2021년 12월 18일

자바

목록 보기
26/41

실습 예제


class Car{
String brand;
String color;
int price;

public Car() {}

public Car(String brand, String color, int price) {
	this.brand = brand;
	this.color = color;
	this.price = price;
}

void engineStart() {
	System.out.println("열쇠로 시동킴");
}

void engineStop() {
	System.out.println("열쇠로 시동끔");
}

}

class SuperCar extends Car{
	String mode;
	
	public SuperCar() {}

	public SuperCar(String brand, String color, int price, String mode) {
		super(brand, color, price);
		this.mode = mode;
	}
	
	
	void ChangeMode(String newMode) {
		this.mode = newMode;
		System.out.println("모드가 바뀌었습니다.");
	}
	
	
	@Override
	void engineStart() {
		System.out.println("음성으로 시동킴");
	}
	@Override
	void engineStop() {
		System.out.println("음성으로 시동 끔");
		
	}
	
	
}

public class CastTest {

public static void main(String[] args) {
	//자식 생성자를 호출함, upcasting 이다
	Car noOptionFerrari = new SuperCar();
	
	//down casting : 오류다
	SuperCar brokenCar = (SuperCar)new Car(); //강제 형변환 해주면 오류는 안나는데 실행하면 오류가남
	
	

}

}

Car car = new Car();
SuperCar ferrari = new SuperCar();

	if(car instanceof Car) {
		System.out.println("nice casting");
	}else {
		System.out.println("err : wrong cast");
	}
profile
우당탕탕 주니어 디벨로퍼

0개의 댓글