Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No enclosing instance of type is accessible [duplicate]

Tags:

java

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:

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;
  } 
}
like image 245
user1896464 Avatar asked Sep 09 '13 02:09

user1896464


2 Answers

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{}
like image 38
upog Avatar answered Nov 08 '22 13:11

upog


MyTriangle is a non-static inner class. That means like all other instance members it (& it's instance) belongs to an instance of the outer class as opposed to the class itself. Remember to belong to a class things need to be defined as static.

Hence, you need to provide an outer class instance to instantiate the inner one as

new OuterClass().new MyTriangle();

If you mark the inner class static which makes it nested it would allow you to refer to it in a static context like a public static main() method.

like image 149
Ravi K Thapliyal Avatar answered Nov 08 '22 11:11

Ravi K Thapliyal