英文:
Strange exception when implementing interface
问题
我遇到了Exception in thread "main" java.lang.NoClassDefFoundError: A(错误名称:a)
错误,我不知道这可能是由什么引起的。
以下是代码部分:
public class Test
{
public static void main(String[] args)
{
new B();
}
}
interface a { }
class A implements a { }
class B extends A { }
备注:在在线编译器https://www.onlinegdb.com/online_java_compiler上编译通过。
英文:
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
答案1
得分: 11
当Java编译您的源代码时,它会创建多个.class
文件。例如,对于public class Test
,它会创建Test.class
;对于interface a
,它会创建a.class
;对于class A
,它会创建A.class
。问题在于,某些操作系统中的文件名不区分大小写。这意味着操作系统将a.class
和A.class
视为相同的文件,因此一个文件将覆盖另一个文件。
在线编译器很可能因为区分大小写而将这些文件名视为不同。
解决方法是使用不同的名称,以避免在操作系统层面上出现这些名称冲突。
既定的Java约定是以大写字母开头的方式命名所有类和接口名称。如果遵循这个约定,您将可以避免这个问题。
英文:
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.
答案2
得分: 1
如果你运行 javac
path/to/your/file
,你应该能够看到 Java 编译器在该目录中创建的 .class
文件列表。你的方法存在问题,即接口和类的名称重复,例如 A(不区分大小写),因此只会创建一个 .class
文件。请尝试通过更改接口或类的名称来解决问题,你的问题应该会消失。
英文:
If you run javac
path/to/your/file
, you should see the list of .class
files 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论