Question

Why is java trowing a NoClassDefFoundError?

The class NestedClassTest has two nested classes, X and Y, inside.

When calling the constructor of NestedClassTest, which instantiates X and Y, java throws an exception when trying to instantiate Y.

public class NestedClassTest {

    private X x = null;
    private Y y = null;

    public NestedClassTest()
    {
        x = new X();
        System.out.println(x.x);
        y = new Y();
        System.out.println(y.y);
    }

    private class X
    {
        public String x = "XXX";
    }

    private class Y
    {
        public String y = "YYY";
    }

    public static void main(String[] args) {
        NestedClassTest t = new NestedClassTest();

    }  
}

This is part of the output:

run:
XXX
Exception in thread "main" java.lang.NoClassDefFoundError: 
    Nestedclasstest/NestedClassTest$Y
    ...
Caused by: java.lang.ClassNotFoundException:
    nestedclasstest.NestedClassTest$Y
    ...
Was it helpful?

Solution 2

Your code is fine.

Looking at your error you might be having troubles with incorrect packages..

 Exception in thread "main" java.lang.NoClassDefFoundError: 
Nestedclasstest/NestedClassTest$Y
...
Caused by: java.lang.ClassNotFoundException:
nestedclasstest.NestedClassTest$Y

nestedclasstest vs Nestedclasstest. Refer here for reference

just recompile and run again, should work.

OTHER TIPS

There is nothing wrong with that, if you are using eclipse, do a Project, Clean and try again, as the build path needs to be updated.

The code you have posted is not incorrect in and of itself. You difficulties lie elsewhere, with compilation or invocation.

You need to include the NestedClassTest$Y class in the classpath.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top