標籤:
今天在編譯Java程式的時候出現以下錯誤:
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).
我原來編寫的原始碼是這樣的:
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);
}
}
出現這個錯誤的時候,我一直不太理解。
在借鑒別人的解釋之後才恍然大悟。
在代碼中,我的Dog類是定義在Main中的內部類。Dog內部類是動態內部類,而我的main方法是static靜態。
就好比靜態方法不能調用動態方法一樣。
有兩種解決辦法:
第一種:
將內部類Dog定義成靜態static的類。
第二種:
將內部類Dog在Main類外邊定義。
修改後的代碼:
第一種:
?
| 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); }} |
第二種:
?
| 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編譯時間出現No enclosing instance of type XXX is accessible.