简体   繁体   中英

Classes with same name

I created a class called Rectangle and placed it into a package that I called 'shapes'. I then created another class called Test, from which I imported both my custom Rectangle class and the java.awt.Rectangle class. Test referred to a Rectangle class. When I tried to compile, I got the message "reference to Rectangle is ambiguous".

However, I then placed my own Rectangle class in the default package (ie no package names declared), and imported the java.awt.Rectangle class as before. At compile time, the compiler used the Rectangle class that was in the default package, not the one that I had imported from the java.awt package.

Any clarification on when there is or is not a clash, and if there isn't, which class the compiler uses, when both file names are the same, would be appreciated.

Here is the code, as requested:

Test class

import java.awt.*;

public class Test {
    public static void main(String[] args) {
        Rectangle r = new Rectangle();
        System.out.println(r.width);
    }
}

Custom Rectangle class

public class Rectangle {

    public int width = 1;

}

Since java 5, you do not need to import classes from default package any longer - which means java does always import all your default classes by "default". This is why it is named like this.

So, what ever you put into a default package, it is imported in all your classes. This may lead to big classes during runtime and unnecessary memory load. It is not wise to put classes into the default package without a very specific reason.

Beside the default package, java also always imports classes from System, String, Integer, Array, Float from the java.lang package. You never had to import these classes, didnt you? Classes in the default package behave the same.

To your solution now, if you want to access the class with the same name, but not within the default package you can always use the full qualified name like package.Class

my.package.MyClass c = new my.package.MyClass();
c.doSomething();

MyClass defaultClass = new MyClass();
defaultClass.doSomethingWithinAClassFromDefaultPackage();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM