No type instance available

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 instance of Question1 type available. A distribution must qualify with an enclosing instance of type Question1 (for example, 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; } } 
+4
source share
2 answers

Try it. Methods removed 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 entered your full code, I assume that your code should look something like this.

Then you must create an instance for your main class before creating an 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{} 
+8
source

MyTriangle is a non-static inner class. This means that all other members of the instance (instance of the instance) belongs to the instance of the outer class, and not to the class itself. Remember to belong to the class, things should be defined as static .

Therefore, you need to provide an instance of the outer class to create the inner copy as

 new OuterClass().new MyTriangle(); 

If you mark the inner static class, which makes it nested, it will allow you to refer to it in a static context, such as the public static main() method.

+15
source

Source: https://habr.com/ru/post/1501233/


All Articles