用Javaclass Animal: def __init__(self): self.sound = "叽里咕噜" def make_sound(self): print(self.sound)class Cat(Animal): def __init__(self): super().__init__() self.sound = "喵喵"class Dog(Animal): def __init__(self): super().__init__() self.sound = "汪汪"class Duck(Animal): def __init__(self): super().__init__() self.sound = "嘎嘎"class Chicken(Animal): def __init__(self): super().__init__() self.sound = "咯咯"# 测试代码animal_name = input("请输入动物名:")if animal_name == "猫": cat = Cat() print("猫 : " + cat.sound)elif animal_name == "狗": dog = Dog() print("狗 : " + dog.sound)elif animal_name == "鸭": duck = Duck() print("鸭 : " + duck.sound)elif animal_name == "鸡": chicken = Chicken() print("鸡 : " + chicken.sound)else: animal = Animal() print(animal_name + " : " + animal.sound)
时间: 2023-05-12 17:07:21 浏览: 109
Animal.java
这段代码定义了一个Animal类和四个子类Cat、Dog、Duck和Chicken。Animal类有一个属性sound和一个方法make_sound,子类继承了Animal类并重写了sound属性。每个子类都有自己的声音,分别是喵喵、汪汪、嘎嘎和咯咯。当调用make_sound方法时,会输出对应子类的声音。
阅读全文