简体   繁体   English

同名课程

[英]Classes with same name

I created a class called Rectangle and placed it into a package that I called 'shapes'. 我创建了一个名为Rectangle的类,并将其放入一个名为“ shapes”的包中。 I then created another class called Test, from which I imported both my custom Rectangle class and the java.awt.Rectangle class. 然后,我创建了另一个名为Test的类,从该类中导入了我的自定义Rectangle类和java.awt.Rectangle类。 Test referred to a Rectangle class. 测试引用到一个Rectangle类。 When I tried to compile, I got the message "reference to Rectangle is ambiguous". 当我尝试编译时,收到消息“对Rectangle的引用不明确”。

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. 但是,然后我将自己的Rectangle类放入默认包中(即未声明任何包名称),并像以前一样导入java.awt.Rectangle类。 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. 在编译时,编译器使用默认包中的Rectangle类,而不是我从java.awt包中导入的类。

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". 从Java 5开始,您不再需要从默认包中导入类-这意味着Java始终会始终通过“默认”导入所有默认类。 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. 除了默认包之外,java还会始终从java.lang包中的System,String,Integer,Array,Float中导入类。 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 现在,对于您的解决方案,如果要访问具有相同名称的类,但不在默认包中访问该类,则始终可以使用完整的合格名称,如package.Class

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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