不能访问封闭的类型实例 [英] No enclosing instance of type is accessible

查看:594
本文介绍了不能访问封闭的类型实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Eclipse中编写了这个Java接口程序,但在 MyTriangle tmp = new MyTriangle(); 下面有一个红线,当我运行程序时出现此错误:

I wrote this Java interface program in Eclipse, but there is a red line under MyTriangle tmp = new MyTriangle(); and when i run the program I get this error:


无法访问Question1类型的封闭实例。必须使用类型为Question1的封闭实例限定
分配(例如
x.new A(),其中x是Question1的实例)。

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).



 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;
  } 
}


推荐答案

尝试这个。为简单起见删除了方法

Try this. Removed the methods for simplicity

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{}






您还没有粘贴完整的代码,我认为您的代码应该如下所示。


You have not pasted your full code, I assume your code should look something like below.

然后您应该为主要代码创建实例在创建三角形实例之前的类,如下所示

Then you should create the Instance for your main class before creating instance for your triangle as shown below

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{}

这篇关于不能访问封闭的类型实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆