No enclosing instance of type is accessible
本问题已经有最佳答案,请猛点这里访问。
我在Eclipse中编写了这个Java接口程序,但是在MyTriangle TMP=新MyTrangangle()下有一条红线;当我运行程序时,我得到了这个错误:
No enclosing instance of type Question1 is accessible. Must qualify
the allocation with an enclosing instance of type Question1 (e.g.
x.new A() where x is an instance of Question1).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public static void main(String[] args) { MyTriangle tmp = new MyTriangle(); tmp.getSides(); System.out.println(); System.out.println("The area of the triangle is" + tmp.computeArea()); } interface Triangle { public void triangle(); public void iniTriangle(int side1, int side2, int side3); public void setSides(int side1, int side2, int side3); public void getSides(); public String typeOfTriangle(); public double computeArea(); } class MyTriangle implements Triangle { private int side1,side2,side3; public void triangle() { this.side1 = 3; this.side2 = 4; this.side3 = 5; } } |
因此,需要提供一个外部类实例来将内部实例实例化为
1 | new OuterClass().new MyTriangle(); |
如果标记使其嵌套的内部类
试试这个。为了简单起见删除了方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class Test1 { public static void main( String [] args) { MyTriangle h1 = new MyTriangle(); } } class MyTriangle implements Triangle{ int side1; int side2; int side3; public MyTriangle(){ this.side1 = 1; this.side2 = 2; this.side3 = 3; } } interface Triangle{} |
您没有粘贴完整的代码,我认为您的代码应该如下所示。
然后您应该在为三角形创建实例之前为您的主类创建实例,如下所示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class Test{ class MyTriangle { int side1,side2,side3; public MyTriangle() { this.side1 = 3; this.side2 = 4; this.side3 = 5; } } public static void main(String[] args) { MyTriangle h1 = new Test(). new MyTriangle(); // Fix is here** } } interface Triangle{} |