首页 > 基础资料 博客日记

Exception in thread “main“ java.lang.Error: Unresolved compilation problem: No enclosing instance

2023-11-23 18:01:27基础资料围观398

Java资料网推荐Exception in thread “main“ java.lang.Error: Unresolved compilation problem: No enclosing instance这篇文章给大家,欢迎收藏Java资料网享受知识的乐趣

JAVA出现“Exception in thread “main” java.lang.Error: Unresolved compilation problem: ”异常处理

代码报错
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
No enclosing instance of type PersonTest is accessible. Must qualify the allocation with an enclosing instance of type PersonTest (e.g. x.new A() where x is an instance of PersonTest).

at com.atguigu.java.PersonTest.main(PersonTest.java:6)

在学习面向对象这一章时,执行以下代码报出来了上述错误,通过查阅资料发现是在java类中,静态方法不能调用动态类,因此,我将类调整为静态,之后就不报错了

package com.atguigu.java;

public class PersonTest {

	public static void main(String[] args) {
		Person p1 =new Person();
		p1.age=5;
		p1.ismale=true;
		p1.name="tom";
		p1.eat();
		p1.talk("Chinese");
		p1.sleep();
		System.out.println(p1.name);
	}
 class Person{
		String name;
		int age;
		boolean ismale;
		public void eat(){
			System.out.println("人会吃饭");
		}
		public void sleep(){
			System.out.println("人会睡觉");
		}
		public void talk(String language){
			System.out.println("人会说"+language+"话");
		}
	}

}

修改之后的代码

public static class Person{
		String name;
		int age;
		boolean ismale;
		public void eat(){
			System.out.println("人会吃饭");
		}
		public void sleep(){
			System.out.println("人会睡觉");
		}
		public void talk(String language){
			System.out.println("人会说"+language+"话");
		}
	}

运行结果就不报错了

另外一种解决方法
先用类声明一个对象,用对象调用方法,这个时候就不会报错了,如下图


文章来源:https://blog.csdn.net/weixin_53661770/article/details/128900572
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云