1

我们之前都是直接创建的类,所以说没有包这个概念,但是现在,我们将类放到包中,就需要注意了:

package com.test; //在放入包中,需要在类的最上面添加package关键字来指明当前类所处的包 public class Main { //将Main类放到com.test这个包中 public static void main(String[] args) { } }

这里又是一个新的关键字package,这个是用于指定当前类所处的包的,注意,所处的包和对应的目录是一一对应的。

不同的类可以放在不同的包下:

当我们使用同一个包中的类时,直接使用即可(之前就是直接使用的,因为都直接在一个缺省的包中)而当我们需要使用其他包中的类时,需要先进行导入才可以:

package com.test; import com.test.entity.Person; //使用import关键字导入其他包中的类 public class Main { public static void main(String[] args) { Person person = new Person(); //只有导入之后才可以使用,否则编译器不知道这个类从哪来的 } }

这里使用了import关键字导入我们需要使用的类,当然,只有在类不在同一个包下时才需要进行导入,如果一个包中有多个类,我们可以使用*表示导入这个包中全部的类:

import com.test.entity.*;

实际上我们之前一直在使用的System类,也是在一个包中的:

package java.lang; import java.io.*; import java.lang.reflect.Executable; import java.lang.annotation.Annotation; import java.security.AccessControlContext; import java.util.Properties; import java.util.PropertyPermission; import java.util.StringTokenizer; import java.util.Map; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.AllPermission; import java.nio.channels.Channel; import java.nio.channels.spi.SelectorProvider; import sun.nio.ch.Interruptible; import sun.reflect.CallerSensitive; import sun.reflect.Reflection; import sun.security.util.SecurityConstants; import sun.reflect.annotation.AnnotationType; import jdk.internal.util.StaticProperty; /** * The <code>System</code> class contains several useful class fields * and methods. It cannot be instantiated. * * <p>Among the facilities provided by the <code>System</code> class * are standard input, standard output, and error output streams; * access to externally defined properties and environment * variables; a means of loading files and libraries; and a utility * method for quickly copying a portion of an array. * * @author unascribed * @since JDK1.0 */ public final class System { ... }

可以看到它是属于java.lang这个包下的类,并且这个类也导入了很多其他包中的类在进行使用。那么,为什么我们在使用这个类时,没有导入呢?实际上Java中会默认导入java.lang这个包下的所有类,因此我们不需要手动指定。

posted @ 2024-02-28 23:14  258333  阅读(5)  评论(0编辑  收藏  举报