【发布时间】:2020-10-07 06:13:21
【问题描述】:
在学校,我被问到这个问题:
前言:在 OOP 中,当一个类的对象被创建时,一个类就被实例化了。分析下面的图 1,并用它来回答下列问题。
使用继承和接口的概念,生成一个类、对象和/或接口的列表,指出:
我。是/是基类、父类或超类。答案是动物课 ii.是/是派生的、子类、子类。对此的答案是鸟类、爬行动物和鱼类类 iii.是/是接口。答案是苍蝇,不要飞,否则会变酸 iv.实现继承的关键字。答案是“扩展” v. 实现接口的关键字。答案是工具。
b) 使用上面的答案,创建一个 Java OOP 程序来实例化所需的对象并调用它们的相关方法。
对于这个问题,我可以写出如下代码:
public class Animal {
public class Animal {
// Properties gender, age, weight
public String gender;
public String age;
public String weight;
// Constructor to inherit for other classes
Animal(String gender, String age, String weight) {
this.gender = gender;
this.age = age;
this.weight = weight;
}
// Methods to inherit
public void sleep() {
System.out.println("Animal can sleep");
}
public void move() {
System.out.println("Animal can move");
}
public void eat() {
System.out.println("Animal can eat");
}
}
//Bird class inherits Animal
class Bird extends Animal {
Bird(String gender, String age, String weight) {
super(gender, age, weight);
}
}
//Reptile Class inherits Animal
class Reptile extends Animal {
Reptile(String gender, String age, String weight) {
super(gender, age, weight);
}
public void leap() {
System.out.println("Frog can leap");
}
Reptile Frog = new Reptile("Male", "1yr", "1kg");
}
//Fish Class inherits Animal
class Fish extends Animal {
Fish(String gender, String age, String weight) {
super(gender, age, weight);
}
Fish Shark = new Fish("Male", "3yrs", "150kg");
}
// Interface Fly
interface abilityToFly {
public void Fly();
}
//Eagle inherits Bird and uses fly ability
class Eagle extends Bird implements abilityToFly {
Eagle(String gender, String age, String weight) {
super("Female", "2yrs", "2kg");
}
@Override
public void Fly() {
System.out.println("It can Fly");
}
}
//Chicken inherits Bird but does not have the ability to fly
class Chicken extends Bird implements abilityToFly {
Chicken(String gender, String age, String weight) {
super("Female", "1yr", "1kg");
}
@Override
public void Fly() {
System.out.println("It can not Fly");
}
}
我不确定我是否以正确的方式完成了此操作,任何人都可以为我更正此代码并告诉我如何实例化它。谢谢
【问题讨论】:
-
青蛙不是爬行动物。现在我得到了我的胸部,看看这篇文章stackoverflow.com/questions/53117364/…
标签: java object inheritance