«   2025/07   »
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 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

장미의 개발일기

메소드 오버라이딩 : 다른 예제 (동물) 본문

개발일기/Java

메소드 오버라이딩 : 다른 예제 (동물)

민장미 2023. 4. 25. 00:46

 

동물 클래스(슈퍼 클래스)

새 클래스, 고양이 클래스, 개 클래스(서브 클래스)

 

 

 

출력해보면 서브클래스의 메소드만 계속 호출되는 것을 알 수 있다.

슈퍼클래스 타입으로 선언해도 오버라이딩이 되어 있다면, 서브클래스의 메소드가 호출된다.

 

package book;

class Animal{
	void cry() {}
}

class Bird extends Animal{
	@Override
	void cry() {
		System.out.println("짹쨱");
	}
}

class Cat extends Animal{
	@Override
	void cry() {
		System.out.println("냐옹");
	}
}

class Dog extends Animal{
	@Override
	void cry() {
		System.out.println("짹쨱");
	}
}


public class Page_335_Ani {
public static void main(String[] args) {
	//각각의 타입으로 선언 + 각각의 타입으로 생성
	Animal aa = new Animal();
	Bird bb = new Bird();
	Cat cc = new Cat();
	Dog dd = new Dog();
	
	aa.cry();
	bb.cry();
	cc.cry();
	dd.cry();
	System.out.println();
	
	// Animal 타입으로 선언 + 자식 클래스 타입으로 생성
	Animal ab = new Bird();
	Animal ac = new Cat();
	Animal ad = new Dog();
	
	ab.cry();
	ac.cry();
	ad.cry();
	System.out.println();
	
	//배열로 관리 
	Animal[] animals = {new Bird(), new Cat(), new Dog()};
	
	for(Animal e: animals) {
		e.cry();
	}
}	
}