The following error occurred while compiling the Java program today:
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 was an instance of main).
The source code I wrote originally was this:
public class Main
{
Class Dog//define a "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);
}
}
I didn't quite understand it when this error occurred.
After drawing on the explanation of others, it dawned on me.
In the code, my dog class is the inner class defined in main. The dog inner class is a dynamic inner class, and my main method is static.
Just as a static method cannot invoke a dynamic method.
There are two ways to solve this problem:
The first type:
The inner class dog is defined as a statically static class.
The second type:
The inner class dog is defined outside the main class.
The Modified code:
The first type:
?
123456789101112131415161718192021222324252627 |
public class Main
{
public static 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
);
}
}
|
The second type:
?
12345678910111213141516171819202122232425262728 |
public class Main
{
public static void main(String[] args)
{
Dog d1 =
new Dog(
"dog1"
,
1
);
}
}
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;}
}
|
Java compilation occurs when no enclosing instance of type XXX is accessible.