今天的学习中老师给的代码成功运行,但是自己对着敲一遍却出现了错误。
错误内容为: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);
尝试过第一种错误未解决,第二种的话成功解决并运行。但是很不理解的是其他代码一样的情况下,为什么自己敲的就会出错。并且将这段代码复制到老师的代码位置中,会报同样的错误。
希望可以得到各位大佬的帮助,理解问题所在。