3
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

4
  • 2
    "Can I not have same class and interface name" No, not like this. Even if you could, you shouldn't want to. Commented Apr 2, 2017 at 5:28
  • You should give classes and interfaces (and methods and variables) meaningful names. Commented Apr 2, 2017 at 5: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")). Commented Apr 2, 2017 at 5:35
  • 4
    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.) Commented Apr 2, 2017 at 6:16

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.