Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange exception when implementing interface

Tags:

java

I have Exception in thread "main" java.lang.NoClassDefFoundError: A (wrong name: a) and I dont't have any idea what this can caused by

public class Test
{
    public static void main(String[] args)
    {
        new B();
    }
}

interface a { }

class A implements a { }

class B extends A { }

Edit: in online compiler https://www.onlinegdb.com/online_java_compiler it compiles

like image 579
Denis_newbie Avatar asked Dec 14 '22 08:12

Denis_newbie


2 Answers

When Java compiles your source code, it creates multiple .class files. For example, it creates Test.class for public class Test, a.class for interface a, and A.class for class A. The problem here is that file names in some operating systems are case-insensitive. This means that the operating system sees a.class and A.class as the same file so one will overwrite the other.

The online compiler most likely treats these file names as different due to case-sensitivity.

The solution here is to use different names so that you avoid these name collisions at the operating system level.

The established Java convention is to start all class and interface names with an upper case letter. If you follow this convention, then you will avoid this problem.

like image 199
Code-Apprentice Avatar answered Dec 15 '22 20:12

Code-Apprentice


If you run javac path/to/your/file, you should see the list of .classfiles created by the java compiler in that dir. The problem with your approach is you have duplicate names for the interface and the class i.e A (case insensitive) and as a result only one .class gets created. Try again by changing the name of either interface or class and your problem should go away.

like image 20
Manish Karki Avatar answered Dec 15 '22 21:12

Manish Karki