Java Error: No enclosing instance of type Main is accessible. Must qualify the allocation with an encl

The following error occurred today while compiling a Java program.
No enclosing instance of type Main is accessible. Must qualify the allocation with an enclosing instance of type Main (e.g. x.new A() where x is an instance of Main).
The source code I originally wrote looked like this

public class Main 
{
class Dog
{
private String name;
private int weight;
public Dog(String name, int weight) 
{
this.setName(name);
this.weight = weight;
}
public int getWeight() 
{
return weight;
}
public void setWeight(int weight) 
{this.weight = weight;}
public void setName(String name)
{this.name = name;}
public String getName() 
{return name;}
}
public static void main(String[] args)
{
Dog d1 = new Dog("dog1",1);

}
}

When this error occurred, I didn’t quite understand it.

After learning from other people’s explanation, I suddenly realized.

In the code, my dog class is an internal class defined in main. The dog inner class is dynamic, while my main method is static.

Just as static methods cannot call dynamic methods.

There are two solutions:

Method 1

Define the inner class dog as a static class.

Method 2

Define the inner class dog outside the main class.

Read More: