Java編譯時間出現No enclosing instance of type XXX is accessible.

來源:互聯網
上載者:User

標籤:

今天在編譯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.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.