Java 상속문제 질문드립니다.
조회수 757회
MainClass를 보고 다음과 같은 output을 얻을수 있도록 inheritance를 이용하여 Animal, Bird, Dog 클래스를 완성하시오. #실행결과#
A new animal has been created!
A new animal has been created!
A new bird has been created!
A new animal has been created!
A new dog has been created!
An animal sleeps...
An animal eats...
A bird sleeps...
A bird eats...
A dog sleeps...
A dog eats...
A new animal has been created!
A new dog has been created!
A new animal has been created!
A new bird has been created!
A dog eats...
A bird sleeps...
public class MainClass {
public static void main(String[] args) {
Animal animal = new Animal();
Bird bird = new Bird();
Dog dog = new Dog();
System.out.println();
animal.sleep();
animal.eat();
bird.sleep();
bird.eat();
dog.sleep();
dog.eat();
Animal a1 = new Dog();
Animal a2 = new Bird();
a1.eat();
a2.sleep();
}
}
public class Animal {
void sleep() { System.out.println("An animal sleeps...");}
void eat() { System.out.println("An animal eats...");}
}
public class Bird extends Animal{
void sleep() { System.out.println("A bird sleeps...");}
void eat() { System.out.println("A bird eats...");}
}
public class Dog extends Animal{
void sleep() { System.out.println("A dog sleeps...");}
void eat() { System.out.println("A dog eats...");}
}
이 문제인데 미완성입니다 ㅠㅠ . MainClass를 건드리지말고 Animal,Dog,Bird 클래스만 수정해야하는데 여기서 어떻게해야할지 모르겠습니다.. 제가 막힌 부분은 저기 위에 실행결과에
A new animal has been created!
A new animal has been created!
A new bird has been created!
A new animal has been created!
A new dog has been created!
이부분과 더 아래에
A new animal has been created!
A new dog has been created!
A new animal has been created!
A new bird has been created! 이 부분을 어떻게 실행해야 할지 감이안옵니다. 살려주세요 ㅠㅠ
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
생성자를 사용하시면 됩니다.
Animal 클래스를 Bird와 Dog 클래스에서 상속받으니 Bird와 Dog 클래스의 객체를 생성할 때는 부모클래스인 Animal의 생성자와 자식클래스인 Bird와 Dog 클래스의 생성자가 실행되게됩니다.
public class Animal { Animal(){ System.out.println("A new animal has been created!"); } void sleep() { System.out.println("An animal sleeps..."); } void eat() { System.out.println("An animal eats..."); } }
public class Bird extends Animal{ Bird(){ System.out.println("A new bird has been created!"); } void sleep() { System.out.println("A bird sleeps..."); } void eat() { System.out.println("A bird eats..."); } }
public class Dog extends Animal{ Dog(){ System.out.println("A new dog has been created!"); } void sleep() { System.out.println("A dog sleeps..."); } void eat() { System.out.println("A dog eats..."); } }
-
(•́ ✖ •̀)
알 수 없는 사용자
-
댓글 입력