不能访问封闭的类型测试实例.必须在简单的测试程序上使用类型为测试错误的封闭实例来限定分配

use*_*466 4 java

我得到了无法封闭的类型测试实例.必须使用类型测试错误的封闭实例限定分配,Location ob1 = new Location(10.0, 20.0);我不知道为什么..

package pkg;

public class test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Location ob1 = new Location(10.0, 20.0);
        Location ob2 = new Location(5.0, 30.0);
        ob1.show();
        ob2.show();
        ob1 = ob1.plus(ob2);
        ob1.show();
        return;
    }

    public class Location // an ADT
    {
        private double longitude, latitude;

        public Location(double lg, double lt) {
            longitude = lg;
            latitude = lt;
        }

        public void show() {
            System.out.println(longitude + " " + latitude);
        }

        public Location plus(Location op2) {
            Location temp = new Location(0.0, 0.0);
            temp.longitude = op2.longitude + this.longitude;
            temp.latitude = op2.latitude + this.latitude;
            return temp;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

upo*_*pog 8

尝试

Location ob1 = new test().new Location(10.0, 20.0);
Location ob2 = new test().new Location(5.0, 30.0);
Run Code Online (Sandbox Code Playgroud)

您需要先创建外部类的实例,然后才能创建内部类的实例


Jop*_*ops 6

您可以考虑将它们分成 2 个文件。看来您的意图不是创建嵌套类,而是让测试类调用您的核心类。

文件 #1:Test.java

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Location ob1 = new Location(10.0, 20.0);
        Location ob2 = new Location(5.0, 30.0);
        ob1.show();
        ob2.show();
        ob1 = ob1.plus(ob2);
        ob1.show();
        return;
    }
 }
Run Code Online (Sandbox Code Playgroud)

文件 #2:Location.java

public class Location // an ADT
{
    private double longitude, latitude;

    public Location(double lg, double lt) {
        longitude = lg;
        latitude = lt;
    }

    public void show() {
        System.out.println(longitude + " " + latitude);
    }

    public Location plus(Location op2) {
        Location temp = new Location(0.0, 0.0);
        temp.longitude = op2.longitude + this.longitude;
        temp.latitude = op2.latitude + this.latitude;
        return temp;
    }
}
Run Code Online (Sandbox Code Playgroud)

当您在单个 java 文件中定义了多个类时,您最终会在它们之间创建依赖关系,因此您会收到错误“封闭类型实例”。在您的代码中,Test包含Location。这些是嵌套类,除非您有很好的设计理由以这种方式编写类,否则最好仍然坚持使用 1-file to 1-class 方法。