[상속-10] 업캐스팅

seratpfk·2022년 8월 1일
0

JAVA

목록 보기
61/96

Person클래스 생성(메인메소드 없음)

	public void eat() {
		System.out.println("먹는다.");
	}
	// Person 타입의 객체가 호출할 수 있도록 메소드 추가
	public void study() {	
	}
	public void work() {	
	}

Student클래스 생성(메인메소드 없음)

public class Student extends Person {
	@Override
	public void study() {
		System.out.println("공부한다.");
	}
}

Alba클래스 생성(메인메소드 없음)

public class Alba extends Student {
	@Override
	public void work() {
		System.out.println("일한다.");
	}
}

Main클래스 생성(메인메소드 설정)

		Person alba = new Alba();
		alba.eat();
		alba.study();
		alba.work();

Person 타입의 배열을 이용

		Person[] people = new Person[10];
		people[0] = new Alba();
		people[1] = new Alba();
		people[2] = new Student();
		for(int i = 0; i < people.length; i++) {
			if(people[i] != null) {
			people[i].eat();
			people[i].study();
			people[i].work();
			}
		}
	// 향상for문
		for(Person person : people) {
			if(person != null) {
				person.eat();
				person.study();
				person.work();
			}

0개의 댓글