最近学习java抽象类和接口,运行书上的例题,出现报错,
No enclosing instance of type Test is accessible. Must qualify the allocation with an enclosing instance of type Test (e.g. x.new A() where x is an instance of Test).
接口:
public interface Edible {
public abstract String howToEat();
}
测试类:
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Object[]object={new Tiger(),new Chicken(),new Apple(),new Orange()};
}
class Animal{
}
class Chicken extends Animal implements Edible{
public String howToEat(){
return "Chicken:Fry it";
}
}
class Tiger extends Animal{
public String howToEat(){
return "Chicken:Fry it";
}
}
abstract class Fruit implements Edible{}
class Apple extends Fruit{
public String howToEat(){
return "Apple:Make apple cider";
}
}
class Orange extends Fruit{
public String howToEat(){
return "Orange:Make orange juice";
}
}
}
你这写的都是内部类吗?如果不是内部类就不会有问题的
在内部类创建对象的时候要求创建外部类的对象。静态方法中不能直接调用非静态方法,必须通过创建对象来调用。
把Test类中的main()方法中改成:
Object[]object={new Test().new Tiger(),new Test().new Chicken(),new Test().new Apple(),new Test().new Orange()};
也可以把new Test()提出来
Test test = new Test();
Object[]object={test.new Tiger(), test.new Chicken(), test.new Apple(), test.new Orange()};