2
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

Irfandy Jip
  • 1,308
  • 1
  • 18
  • 36
Ankit
  • 271
  • 3
  • 11
  • 2
    "_Can I not have same class and interface name_" No, not like this. Even if you could, you shouldn't want to. – takendarkk Apr 02 '17 at 05:28
  • You should give classes and interfaces (and methods and variables) meaningful names. – Guy Apr 02 '17 at 05:30
  • An interface *is* a special type of abstract class. That’s why you can write `System.out.println(Runnable.class)` and `System.out.println(Class.forName("java.lang.Runnable"))`. – VGR Apr 02 '17 at 05:35
  • 3
    To the people downvoting, voting to close: this is a legitimate question, and (according to my search) not a duplicate. The fact that it indicates that the OP has misunderstood something pretty fundamental about classes and interfaces (that they are named in the same namespace) does not make it a bad Question. (OK: if the OP could have researched this better. However, consider that SO is supposed to be a place to find Answers ... and there wasn't one here for this Question.) – Stephen C Apr 02 '17 at 06:16

2 Answers2

6

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.

Wyzard
  • 33,849
  • 3
  • 67
  • 87
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.

Ofir Winegarten
  • 9,215
  • 2
  • 21
  • 27