前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java-No enclosing instance of type TestExtends is accessible.的错误纠正

Java-No enclosing instance of type TestExtends is accessible.的错误纠正

作者头像
Fisherman渔夫
发布2019-07-30 17:41:23
5960
发布2019-07-30 17:41:23
举报
文章被收录于专栏:渔夫渔夫
代码语言:javascript
复制
public class TestExtends {
public static void main(String[] args){

Boy boy1 =new Boy();
boy1.name="李寻欢";
boy1.Hobby="playing basketball!";
boy1.play();
boy1.rest();
}

class Person{
String name;
int height;
public void rest(){
	System.out.println("休息一会儿");
}
}
class Boy extends Person{
String Hobby;
public void play(){
	System.out.println("玩一下篮球!");
}
}
}

这个错误是我在进行Java继承学习时候遇到的,但是此错误和继承并没有关系。这里Run一下会出现错误,No enclosing instance of type TestExtends is accessible. Must qualify the allocation with an enclosing instance of type TestExtends (e.g. x.new A() where x is an instance of TestExtends).提醒,后来经过查找资料,发现我这里定义的Boy是main中的内部类,Boy是被定义的动态类,而我得main方法是静态的。

由于Java有个重要的性质,静态的方法不能调用动态的方法,类比为定义在TestExtends这个类内,而这个类内部定义的类是动态的,而main方法是静态的,静态的不能调用动态的,所以有两个方法: 1)我们把Boy这个类置于TestExtends这个类外面定义此类。也就是写的时候要注意{}大括号的使用。

2)还是将Boy这个类定义在TestExtends类里,但是将其定义为Static类

代码语言:javascript
复制
public class TestExtends {
public static void main(String[] args){

Boy boy1 =new Boy();
boy1.name="李寻欢";
boy1.Hobby="playing basketball!";
boy1.play();
boy1.rest();
	}
static class Person{
String name;
int height;
public void rest(){
	System.out.println("休息一会儿");
	}
}
static class Boy extends Person{
String Hobby;
public void play(){
	System.out.println("玩一下篮球!");
		}
	}
}	

且注意,Boy继承(extends)的Person类也必须得静态,否则Boy就也无法继承了。所以静态的类、方法不能调用动态的类和方法,这点切记。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年03月29日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档