学习中的问题:No enclosing instance of type Test_drive is accessible. Must qualify the allocation with an e

今天的学习中老师给的代码成功运行,但是自己对着敲一遍却出现了错误。

错误内容为:No enclosing instance of type Test_drive is accessible. Must qualify the allocation with an enclosing instance of type Test_drive (e.g. x.new A() where x is an instance of Test_drive).

翻译:无法访问类型测试驱动器的封闭实例。必须使用类型为test_drive的封闭实例限定分配(例如x.new a(),其中x是test_drive的实例)。

错误出现在了    Shape s1=new Rectangle(2, 4);   这一段代码!!!

代码如下:

package com.zzc.www;

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Shape s1=new Rectangle(2, 4);
		//修改后
//		Test td = new Test();
//		Shape s1=td.new Rectangle(2, 4);
//		System.out.println(s1.getGirth());
//		System.out.println(s1.getArea());
	}
	
	 class Shape{
		private double length;
		private double width;
		public Shape(double length, double width) {
			this.length = length;
			this.width = width;
		}
		
		
		public double getLength() {
			return length;
		}
		public void setLength(double length) {
			this.length = length;
		}
		public double getWidth() {
			return width;
		}
		public void setWidth(double width) {
			this.width = width;
		}
		//
		public double getGirth(){
			return 0.0;
		}
		public double getArea(){
			return 0.0;
		}	
	}
	
	 class Rectangle extends Shape{

		public Rectangle(double length, double width) {
			super(length, width);
			// TODO Auto-generated constructor stub
		}
		public double getGirth(){
			return (this.getLength()+this.getWidth())*2;
		}
		public double getArea(){
			return this.getLength()*this.getWidth();
		}
	}
	 class Square extends Rectangle{

		public Square(double length) {
			super(length, length);
			// TODO Auto-generated constructor stub
		}
		
	}
	
	 class Circle extends Shape{

		public Circle(double r) {
			super(r, r);
			// TODO Auto-generated constructor stub
		}
		public double getGirth(){
			return 2*3.14*this.getLength();
		}
		public double getArea(){
			return 3.14*this.getLength()*this.getLength();
		}
	}
	
}	

遇到问题要及时解决,所以在网上查找了关于这个问题出现的原因及解决方法。

原因如下:内部类不是静态内部类,是动态的,而main方法是静态的。在直接赋值,程序报错。

修改方法查到有两种:

(1)将内部类定义为static,即为静态类

(2)将Shape s1=new Rectangle(2, 4);

          改为Test td = new Test();

                  Shape s1=td.new Rectangle(2, 4);

尝试过第一种错误未解决,第二种的话成功解决并运行。但是很不理解的是其他代码一样的情况下,为什么自己敲的就会出错。并且将这段代码复制到老师的代码位置中,会报同样的错误。

希望可以得到各位大佬的帮助,理解问题所在。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值