Java Class and Interface Name Collision

蹲街弑〆低调 提交于 2020-12-13 04:16:49

问题


interface A
{
void print();
}


class A implements A
{

public void print()
{
System.out.println("Hello");
}

public static void main(String args[])
{
A a=new A();
a.print();
}

}

When i am using this code then it is saying "duplicate class:A". Why so? Can I not have same class and interface name


回答1:


You can't have a class and an interface with the same name because the Java language doesn't allow it.

First of all, it's ambiguous. If you declare a variable like this:

A a;

What is the type of that variable? Is it the class, or the interface?

Second, compiled Java code is stored in .class files named after the class or interface defined in the file. An interface named A and a class named A would both compile to a file named A.class. You can't have two files with the same name in the same folder.

The error message says "duplicate class" because Java internally treats an interface as a special kind of class.




回答2:


The fully qualified name of a class and interface consist of the package name and the class/interface name only.

So if your package name is com.foo.bar, both the interface and the class names would be: com.foo.bar.A

Under different packages you can have the same names of course.



来源:https://stackoverflow.com/questions/43164923/java-class-and-interface-name-collision

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!