本文介绍了我是否必须使用"package"每堂课都学期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我尝试使用 Java,第4版入门指南来学习Java.我使用Ubuntu作为我的操作系统,并使用Netbeans作为我的IDE.使用Netbeans时,我需要创建一个项目来创建一个类.

Firstly, I'm trying to learn Java with Java, A Beginner's Guide, 4th Edition. I use Ubuntu as my OS and Netbeans as my IDE. I need to create a project to create a class when using Netbeans.

这是我的世界应用程序.

Here is my hello world app.

class First{
    public static void main(String args[])
    {
        System.out.println("Hello!");
    }   
}

但是这会返回很多错误.当我将 package首先; 行放在Java类的顶行时,它将运行.但是,这本书没有使用打包术语.这是Netbeans的规则,还是我需要了解的什么?

But this returns a lot of errors. When I put package first; line to top line of my Java class it runs. But, the book isn't using package term. Is this a rule of Netbeans, or what I need to know about this?

推荐答案

您永远不需要将类放入包中.但是,这几乎总是一个好主意.这是Netbeans积极鼓励您去做的事情.

You never need to put a class in a package. However, it is almost always a good idea. This is something that Netbeans aggressively tries to encourage you to do.

对于小型项目,使用默认程序包(即没有 package 语句的文件)是可以的.但是,一旦您的项目扩展并开始添加外部库,就会发生不好的事情.如果其他人决定使用默认程序包并且碰巧有一个同名类,该怎么办?现在,由于您都在同一个程序包中,因此可能会发生冲突!

For small projects, using the default package (that is, a file without a package statement) is OK. However, once your project grows and starts adding external libraries, bad things can happen. What if someone else decided to use the default package and happened to have an identically-named class? Now, since you're both in the same package, collisions can occur!

您的文件结构也应反映您的软件包.也就是说,包com.myurl.helloworld 中的文件应位于名为 com/myurl/helloworld 的文件夹中.这是由于与上述相同的原因.

Your file structure should also reflect your package. That is, a file in package com.myurl.helloworld should be located in a folder called com/myurl/helloworld. This is for the same reasons as above.

而且,您可能尚未在这里学习,您无法从默认程序包中导入类,也不能在默认程序包类中使用程序包专用的可见性修饰符.

Also, and you probably haven't gotten here in your studies, you cannot import classes from the default package, or use the package-private visibility modifier in a default package class.

这篇关于我是否必须使用"package"每堂课都学期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 09:59