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 Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Java 8引入了Stream API,提供了一种强大且表达力丰富的处理数据集合的方式。然而,使用Stream时,一个常见问题是:如何从forEach操作中中断或返回? 传统循环允许提前中断或返回,但Stream的forEach方法并不直接支持这种方式。本文将解释原因,并探讨在Stream处理系统中实现提前终止的替代方法。 延伸阅读: Java Stream API改进 理解Stream forEach forEach方法是一个终端操作,它对Stream中的每个元素执行一个操作。它的设计意图是处
