0

I'm having trouble in my main method. On the line MyInt r1 = new MyInt(2); I get a compiler error with the message: "No enclosing instance of type ex4 is accessible".

public class ex4 {
    public class MyInt implements Comparable<MyInt> { 
        private int value;

        MyInt(int x){ this.value= x;}

        public String toString() {
            return ("Result: " + intValue());
        }

        public int intValue() { return value; }

        public int compareTo(MyInt rhs){
            if ( value >rhs.value ){
                return 1;}
            if (value < rhs.value){
                return -1;}
            else return  0;
        }
    }

    public static void main(String[] args) {
        MyInt r1 = new MyInt(2); //Error here ("No enclosing instance of type ex4 is accessible. Must qualify the allocation with an enclosing instance of type ex4 (e.g. x.new A() where x is an instance of ex4)."
        MyInt r2 = new MyInt(7); // same here
        System.out.println(r1.compareTo(r2));
    }
}

I've seen other responses to similar questions but I'm unable to solve my own issue, could anyone help? I'm trying to compare one value to another. Thanks.

Andy Brown
  • 18,961
  • 3
  • 52
  • 62
Corzuu
  • 91
  • 1
  • 10
  • What is your actual issue? – David says Reinstate Monica Feb 04 '15 at 18:04
  • Possible duplicate of [No enclosing instance of type Server is accessible](http://stackoverflow.com/questions/7901941/no-enclosing-instance-of-type-server-is-accessible) – Raedwald Mar 02 '16 at 22:33
  • Possible duplicate of [Java - No enclosing instance of type Foo is accessible](http://stackoverflow.com/questions/9560600/java-no-enclosing-instance-of-type-foo-is-accessible) – fabian Mar 03 '16 at 22:05

1 Answers1

0

MyInt is declared as an inner class, and can't be used in a static context. Change it to:

public static class MyInt 

From the Java Tutorials:

A static nested class is associated with it's outer class, and is static.

An inner class is associated with an instance of it's enclosing class.

The relevant section of the JLS is §8.1.3:

An inner class is a nested class that is not explicitly or implicitly declared static.

Andy Brown
  • 18,961
  • 3
  • 52
  • 62