Java编译时出现 No enclosing instance of type Main is accessi
今天在编译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). 我原来编写的源代码是这样的: publ
今天在编译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类外边定义。
修改后的代码:
第一种:
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); } }
第二种:
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;} }

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











Java の乱数ジェネレーターのガイド。ここでは、Java の関数について例を挙げて説明し、2 つの異なるジェネレーターについて例を挙げて説明します。

Java の Weka へのガイド。ここでは、weka java の概要、使い方、プラットフォームの種類、利点について例を交えて説明します。

Java のアームストロング番号に関するガイド。ここでは、Java でのアームストロング数の概要とコードの一部について説明します。

この記事では、Java Spring の面接で最もよく聞かれる質問とその詳細な回答をまとめました。面接を突破できるように。

Java 8は、Stream APIを導入し、データ収集を処理する強力で表現力のある方法を提供します。ただし、ストリームを使用する際の一般的な質問は次のとおりです。 従来のループにより、早期の中断やリターンが可能になりますが、StreamのForeachメソッドはこの方法を直接サポートしていません。この記事では、理由を説明し、ストリーム処理システムに早期終了を実装するための代替方法を調査します。 さらに読み取り:JavaストリームAPIの改善 ストリームを理解してください Foreachメソッドは、ストリーム内の各要素で1つの操作を実行する端末操作です。その設計意図はです
