Search code examples
javaruntime-errorinner-classesmain-method

Error when executing Java code with nested class


newbie here. Tried executing Java class that has a nested class and I keep getting this Error: Could not find or load main class . Caused by: java.lang.ClassNotFoundException When I compiled the source code, I got two new .class files; ShadowTest$FirstLevel.class and ShadowTest.class. The error shows up when I try to execute either one. Please help.

Here's the code

public class ShadowTest {

    public int x = 0;

    class FirstLevel {

        public int x = 1;

        void methodInFirstLevel(int x) {
            System.out.println("x = " + x);
            System.out.println("this.x = " + this.x);
            System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
        }
    }

    public static void main(String... args) {
        ShadowTest st = new ShadowTest();
        ShadowTest.FirstLevel fl = st.new FirstLevel();
        fl.methodInFirstLevel(23);
    }
}

Solution

  • You can always compile the class with javac filename command. Then execute the code with command java main_class_name

    javac ShadowTest.java
    java ShadowTest
    

    /** output **/

    x = 23
    this.x = 1
    ShadowTest.this.x = 0
    

    Inner classes, if any present in your class, will be compiled and the class file will be ClassName$InnerClassName.