编译时提示第七行, master ms = new master(); ms.feed(new Dog(), new Bone()) new Bone()出错,错误提示是以下。 No enclosing instance of type duotai is accessible. Must qualify the allocation with an enclosing instance of type duotai (e.g. x.new A() where x is an instance of duotai)
你的food类是内部类,把他移到外面就和animal一样了
错误信息不是说明的挺清楚的嘛,你没有设置外部实例引用。 修改main方法代码如下: public static void main(String[] args) { duotai dt = new duotai(); master ms = new master(); ms.feed(new Dog(), dt.new Bone()); }
用这个可以运行package zicheng;public class duotai{ public static void main(String[] args) { master ms = new master(); ms.feed(new Dog(), new Bone()); } // 主人类 static class master { public void feed(Animal an, Food fd) { an.eat(); fd.showname(); } } } // 食物类 class Food { String name; public void showname() { System.out.println("食物"); } } class Fish extends Food { public void showname() { System.out.println("鱼"); } } class Bone extends Food { public void showname() { System.out.println("骨头"); } } // 动物类 class Animal { int age; String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void cry() { System.out.println("动物叫呀动物叫"); } public void eat() { } }class Dog extends Animal { public void cry() { System.out.println("汪汪叫!"); } public void eat() { System.out.println("够爱吃骨头"); }}class Cat extends Animal { public void cry() { System.out.println("喵喵叫!"); } public void eat() { System.out.println("猫爱吃鱼"); } }
ms.feed(new Dog(), new Bone())
new Bone()出错,错误提示是以下。
No enclosing instance of type duotai is accessible. Must qualify the allocation with an enclosing instance of type duotai (e.g. x.new A() where x is an instance of duotai)
修改main方法代码如下:
public static void main(String[] args) {
duotai dt = new duotai();
master ms = new master();
ms.feed(new Dog(), dt.new Bone());
}
public static void main(String[] args) {
master ms = new master();
ms.feed(new Dog(), new Bone());
} // 主人类 static class master {
public void feed(Animal an, Food fd) {
an.eat();
fd.showname();
}
}
} // 食物类
class Food {
String name; public void showname() {
System.out.println("食物");
}
} class Fish extends Food {
public void showname() {
System.out.println("鱼");
}
} class Bone extends Food {
public void showname() {
System.out.println("骨头");
}
}
// 动物类
class Animal {
int age;
String name; public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public void cry() {
System.out.println("动物叫呀动物叫");
} public void eat() { }
}class Dog extends Animal { public void cry() {
System.out.println("汪汪叫!");
} public void eat() {
System.out.println("够爱吃骨头");
}}class Cat extends Animal {
public void cry() {
System.out.println("喵喵叫!");
} public void eat() {
System.out.println("猫爱吃鱼");
}
}