在学校里,有人问我这个问题:
序言:在OOP中,当创建该类的对象时,该类被称为实例化。分析下面的图1,并将其用于回答以下问题。
使用继承和接口的概念,生成类,对象和/或接口的列表,指示:
一世。是基类,父类或超类。答案是动物类ii。是派生的,孩子的,子类。答案是鸟类,爬行动物和鱼类iii。是接口。答案是“不飞”或“会酸高”。用于实现继承的关键字。答案是“扩展” 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");
}
}
我不确定我是否以正确的方式完成此操作,是否有人可以为我更正此代码并告诉我如何实例化它。谢谢
归纳概括,几乎没有什么改变。
您已Encapsulation, inheritance
正确完成。您可以处理以下事情,也没有什么改进的方法。
Reptile
并且Fish
应该是一个班级extends Animal
。Frog
应该是另一个类,leap
它本身具有其他属性。相似地Fish
我不确定这些分类。根据class
图表,我正在oops concepts
向您解释。
n
许多reptiles
每个人可以有自己的行为。假设reptile1
吃饭时有声音,reptile2
但没有时却有声音。因此,您可以进行以下操作。
public abstract Reptile extends Animal{
public abstract leap();
}
public class Reptile1 extends Reptile {
//Define leap behaviour
//Define other behaviour and characteristics
}
public class Reptile2 extends Reptile {
//Define leap behaviour
//Define other behaviour and characteristics
}
在实例化时,您可以Reptile frog = new Frog();
-polymorphism
private
并添加getter, setters
。--Abstraction
private String gender; private String age; private String weight; public String getGender() { return gender; } public void setGender(String gender) { //validate if needed - only accepted genders //to avoid malformed data/input this.gender = gender; }
Chicken
不需要实现fly
接口,因为它不能实现这种行为。除了这些,你initialisation
看起来还不错。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句