Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

I got the No enclosing instance of type test is accessible. Must qualify the allocation with an enclosing instance of type test error with Location ob1 = new Location(10.0, 20.0); I'm not sure why..

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;
        }
    }
}
like image 565
user133466 Avatar asked Oct 02 '13 16:10

user133466


People also ask

What does no enclosing instance mean in Java?

The java No enclosing instance of type is accessible. Must qualify the allocation with an enclosing instance of type (e.g. x.new A() where x is an instance of ). exception happens when an instance is created for an inner class in the outer class static method.


1 Answers

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

like image 116
upog Avatar answered Sep 22 '22 11:09

upog