Frog is cry

다형성, instanceOf(Day22) 본문

JAVA/국비수업

다형성, instanceOf(Day22)

Frog is cry 2020. 7. 30. 19:02
package day24.ex01;

public class Taxi extends Vehicle{
	@Override
	public void run() {
		System.out.println("택시가 달립니다.");
	}
}
package day24.ex01;

public class Driver {
	public void drive(Vehicle vehicle) {
		// drive 메소드의 정의부에 사용한 매개변수를
		// Vehicle 클래스의 vehicle참조변수로 지정함.
		vehicle.run();	// Vehicle 클래스에 정의된
						// run 메소드를 호출함
		
	}
	
}
package day24.ex01;

public class Bus extends Vehicle{
	@Override
	public void run() {
		System.out.println("버스가 달립니다.");
	}
}
package day24.ex01;

public class Vehicle {
	public void run() {
		System.out.println("차량이 달립니다.");
	}
}
package day24.ex01;

public class Vehicle_Ex {
	public static void main(String[] args) {
		Driver driver = new Driver();
		
		Bus bus = new Bus();
		Taxi taxi = new Taxi();
		
		driver.drive(bus);
		driver.drive(taxi);
		
		Vehicle v1 = new Vehicle();
		
		driver.drive(v1);
	}
}

 

instanceOf

package day24.ex04_instanceof;

public class Child_Ex {
		public static void method1(Parent parent) {
			if(parent instanceof Child) {
				Child child = (Child)parent;
				System.out.println("method1-Child로 변환성공");
			}else {
				System.out.println("method1-Child로 변환되지 않음");
			}
		}

	public static void method2(Parent parent) {
		Child child = (Child)parent;
		System.out.println("method-child로 변환 성공");
	}
	
	public static void main(String[] args) {
		Parent parentA = new Child();
		method1(parentA);
		method2(parentA);
	}
	
}

'JAVA > 국비수업' 카테고리의 다른 글

interface(day24)  (0) 2020.07.31
instanceOf(day24)  (0) 2020.07.31
캐스팅(day22)  (0) 2020.07.29
protected(day21)  (0) 2020.07.28
final(day21)  (0) 2020.07.28
Comments