20210803) 상속 - 다형성(Polymorphism)

0

JAVA

목록 보기
61/71

패키지를 만든 후 오버라이딩메소드에서 클래스들을 복사 붙이기

집고양이 길고양이 호랑이 클래스는 모두 고양이 클래스를 상속 받았으므로 고양이 클래스로 선언 가능

App

package polymorphism;

public class App {

	public static void main(String[] args) {
		
		Cat cat1 = new HouseCat();

		cat1.vocal();
		cat1.hunt();
        
       	Cat cat2 = new RoadCat();

		cat2.vocal();
		cat2.hunt();

		Cat cat3 = new Tiger();
		cat3.vocal();
		cat3.hunt();
		
	}
}

그러면 Cat 클래스의 배열 cats로 만들어
cat1, cat2, cat3 대신 cats[0], cat[1], cat[2] 로 사용


package polymorphism;

public class App {

	public static void main(String[] args) {
		
		Cat[] cats = {new HouseCat(), new RoadCat(), new Tiger() };
//		Cats[0]  == new HouseCat();
//		Cats[1]  == new RoadCat();
//		Cats[2]  == new Tiger();

	
		cats[0].vocal();
		cats[0].hunt();

		cats[1].vocal();
		cats[1].hunt();

		cats[2].vocal();
		cats[2].hunt();
	
	}
}

반복문 사용

for(int i=0 ; i<cats.length; i++) {
			cats[i].vocal();
			cats[i].hunt();
		}

for each 반복문

for(Cat cat : cats) {
			cat.vocal();
			cat.hunt();
		}

0개의 댓글

Powered by GraphCDN, the GraphQL CDN