用Java创建动物类,其叫声为输出“叽里咕噜”,猫类,狗类,鸭类,鸡类继承动物类,分别发出叫声“喵喵”,“汪汪”,“嘎嘎”,“咯咯”,输入动物名,输出相应动物叫声
时间: 2023-05-18 08:03:28 浏览: 161
好的,以下是Java代码:
```
public class Animal {
public void makeSound() {
System.out.println("叽里咕噜");
}
}
public class Cat extends Animal {
public void makeSound() {
System.out.println("喵喵");
}
}
public class Dog extends Animal {
public void makeSound
相关问题
java猫狗继承动物类
以下是Java中猫狗继承动物类的例子:
引用中的猫类继承自动物类Animal,具有自己的eat()方法,可以通过以下代码进行调用:
```java
public class Cat extends Animal {
public Cat() { }
public Cat(String name, int age) {
super(name, age);
}
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}
```
引用中的猫类和狗类都继承自动物类Animal,具有自己的方法,可以通过以下代码进行调用:
```java
class Cat extends Animal{
public Cat() { }
public Cat(String name, int age) {
super(name, age);
}
public void catchMouse(){
System.out.println("猫抓老鼠");
}
}
class Dog extends Animal{
public Dog() { }
public Dog(String name, int age) {
super(name, age);
}
public void lookdoor(){
System.out.println("狗看门");
}
}
```
创建动物类,其叫声为输出“叽里咕噜”,猫类,狗类,鸭类,鸡类继承动物类,分别发出叫声“喵喵”,“汪汪”,“嘎嘎”,“咯咯”,输入动物名,输出相应动物叫声,输出格式为“动物名 : 动物叫声\n“java实现
以下是Java实现:
```java
class Animal {
public void makeSound() {
System.out.println("叽里咕噜");
}
}
class Cat extends Animal {
public void makeSound() {
System.out.println("喵喵");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("汪汪");
}
}
class Duck extends Animal {
public void makeSound() {
System.out.println("嘎嘎");
}
}
class Chicken extends Animal {
public void makeSound() {
System.out.println("咯咯");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = null;
String name = "猫";
if (name.equals("猫")) {
animal = new Cat();
} else if (name.equals("狗")) {
animal = new Dog();
} else if (name.equals("鸭")) {
animal = new Duck();
} else if (name.equals("鸡")) {
animal = new Chicken();
} else {
System.out.println("未知动物");
}
if (animal != null) {
System.out.println(name + " : ");
animal.makeSound();
}
}
}
```
运行结果:
```
猫 :
喵喵
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)