如何从Dog类中获取实例变量hitpoint,并通过eat( x )方法将它们传递给Lion类?
我试图让Lion吃() Lion类中存储在一个新变量中的实例变量中的Dog和减号。
狮类
package helloworld;
public class Lion {
public String name;
public int heightCMeters;
public int lengthCMeters;
public float weightKilos;
public int hitPoints;
public Lion(int hitPoints, String name, int heightCMeters, int lengthCMeters, float weightKilos) {
this.name = name;
this.heightCMeters = heightCMeters;
this.lengthCMeters = lengthCMeters;
this.weightKilos = weightKilos;
}
public void lionDetails() {
System.out.println("Name: " + this.name);
System.out.println("Height CM: " + this.heightCMeters);
System.out.println("Length CM: " + this.lengthCMeters);
System.out.println("Weight Kilos: " + this.weightKilos);
}
public void eat(X x) {
int hitPoints = x.hitPoints - 10;
System.out.println(x)
}
}类犬
package helloworld;
public class Dog {
public String name;
public int heightCMeters;
public int lengthCMeters;
public float weightKilos;
public int hitPoints;
public Dog(int hitPoints, String name, int heightCMeters, int lengthCMeters, float weightKilos) {
this.name = name;
this.heightCMeters = heightCMeters;
this.lengthCMeters = lengthCMeters;
this.weightKilos = weightKilos;
}
public void dogDetails() {
System.out.println("Name: " + this.name);
System.out.println("Height CM: " + this.heightCMeters);
System.out.println("Length CM: " + this.lengthCMeters);
System.out.println("Weight Kilos: " + this.weightKilos);
}
public void eat(X x) {
int hitPoints = x.hitPoints - 10;
System.out.println(x)
}
}发布于 2013-12-18 10:22:33
基本上,狮子可以吃狗,而相反的是事实(这很奇怪,狗没有足够的勇气攻击狮子)。无论如何,您需要的是一个代表吃动物的动物的abstract class,这个类应该包含您提到的hitPoint。
abstract class X {
public int hitPoints;
}
// Lions are edible
class Lion extends X{
public void eat(X x) { // pass an edible object
int hitPoints = x.hitPoints - 10;
System.out.println(x)
}
}
//Dogs are edible as well
class Dog extends X{
public void eat(X x) { // pass an edible object
int hitPoints = x.hitPoints - 10;
System.out.println(x)
}
}现在,狮子要吃狗,
Lion predator = new Lion();
Dog prey = new Dog();
predators.eat(prey); // this passed dog will be eaten 发布于 2013-12-18 10:18:02
最好的方法是为Lion类编写测试类或编写主要方法,这将维护两个类的命中点。
class Test{
public static void main(String[] args){
Dog puppy=new Dog(10,"Moti",12,12,31);
Lion oldLion=new Lion(20,"Old Lion",12,12,43);
oldLion.eat(puppy);
}
}发布于 2013-12-18 10:21:52
您必须有一个抽象类Animal,,其中定义了所有公共方法。
对于eat方法的Lion类,
public void eat (Animal animal) {
this.hitPoints-=animal.hitPoints;
}对于eat方法的Dog类,也有相同的逻辑。
https://stackoverflow.com/questions/20655131
复制相似问题