导入包是否会改变类的可见性? [英] Does importing of packages change visibility of classes?

查看:194
本文介绍了导入包是否会改变类的可见性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我jsut了解到


可以使用
修饰符public声明一个类,在这种情况下
类对于所有类都是可见的
无处不在。如果一个类没有修饰符
(默认值,也称为
package-private),它在自己的包中只能看到

A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package.

这是一个明确的陈述。但是这些信息干扰了我对包裹进口的理解(这很容易就是错误的)。我认为导入一个包我从导入包中可以看到导入类的类。

This is a clear statement. But this information interfere with my understanding of importing of packages (which easily can be wrong). I thought that importing a package I make classes from the imported package visible to the importing class.

那么,它是如何工作的?是否所有类的公共类都可以在条件下导入包含公共类的包?还是没有这样的条件?包私有类怎么样?如果包含的包装是否被导入,它们是不可见的?

So, how does it work? Are public classes visible to all classes everywhere under condition that the package containing the public class is imported? Or there is not such a condition? What about the package-private classes? They are invisible no mater if the containing package was imported or not?

增加:
在我看来,我得到了2个被标记为良好的答案(并且相互矛盾。

ADDED: It seems to me that I got 2 answers which are marked as good (up-voted) and which contradict eachother.

推荐答案

导入类不会以任何方式改变其可见性。将类导入到另一个类或多或少只是一种使源代码可读的方法,因此您不必一直输入完全限定的类。例如,这个类

Importing a class doesn't change its visibility in any way. Importing a class to another class is more or less just a way to make your source code readable so you don't have to put in fully qualified class all the time. For example this class

import java.util.*;

class ImportTests {
    private Collection collection;
}

编译成与此类相同的代码

compiles to the same code that this class would

class ImportTests {
    private java.util.Collection collection;
}

import 声明在第一个类中,它不会改变 Collection java.util 包中的任何其他类的可见性使得 ImportTests 类可以引用 Collection 而不使用完全限定名。

The import statement in the first class doesn't change the visibility of Collection or any other class inside the java.util package it just makes it so the ImportTests class can reference Collection without the fully qualified name.

这篇关于导入包是否会改变类的可见性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆