Ankit
Ankit

Reputation: 275

Java Class and Interface Name Collision

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

Upvotes: 3

Views: 5714

Answers (2)

Ofir Winegarten
Ofir Winegarten

Reputation: 9365

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.

Upvotes: 2

Wyzard
Wyzard

Reputation: 34571

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.

Upvotes: 7

Related Questions