Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 505
Ankit Avatar asked Apr 29 '26 08:04

Ankit


1 Answers

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.

like image 174
Wyzard Avatar answered May 01 '26 21:05

Wyzard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!