No enclosing instance of type test is accessible. Must qualify the allocation with an enclosing instance of type test error on a simple test Program

try

Location ob1 = new test().new Location(10.0, 20.0);
Location ob2 = new test().new Location(5.0, 30.0);

you need to create an instance of outer class first, then you can create an instance of inner class


You may consider splitting them into 2 files. It appears that your intention is not to create nested classes, but rather having a tester class calling your core class.

File #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;
    }
 }

File #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;
    }
}

When you have multiple classes defined inside a single java file, you end up creating dependencies between them, thus you're getting the error "enclosing instance of type". In your code, Test is enclosing Location. These are nested classes and unless you have good design reasons to write your classes that way, it's still best to stick to the 1-file to 1-class approach.

Tags:

Java