-1

What did I do wrong here? Need to print -1 and 100 but I keep getting this error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: No enclosing instance of type Main is accessible. Must qualify the allocation with an enclosing instance of type Main (e.g. x.new A() where x is an instance of Main). at Main.main(Main.java:3)

    public static void main(String[] args) {
        MyClass a = new MyClass();
        MyClass b = new MyClass(100);
        System.out.println(a.getValue()); // -1
        System.out.println(b.getValue()); // 100
    }
    public class MyClass {
        private int value;
        // Constructors
        public MyClass() {
            value = -1;
        }
        
        public MyClass(int x) {
            value = x;
        }
        
        public int getValue() {
            return value;
        }
    }
}

1 Answers1

0

Your problem is that your main method has no class. Here you have an example:

public class Main {
    public static void main(String[] args) {
        MyClass a = new MyClass();
        MyClass b = new MyClass(100);
        System.out.println(a.getValue()); // -1
        System.out.println(b.getValue()); // 100
    }
}
class MyClass {
    private int value;
    // Constructors
    public MyClass() {
        value = -1;
    }
    
    public MyClass(int x) {
        value = x;
    }
    
    public int getValue() {
        return value;
    }
}

You can also create some inner classes, as explained here: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

But, if you are starting as a programmer, I don't recommend you to create neither inner nor outer classes, and rather create a new class. Something like:

org.demo.myclasses.Main ==> This is your Main class with your main method.

org.demo.myclasses.MyClass ==> Another different file for your new class.

Here's another question made by another user with more info about it: Java inner class and static nested class