Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to use "package" term in every class?

Tags:

java

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!");
    }   
}

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?

like image 684
Yusuf Avatar asked Jul 22 '13 21:07

Yusuf


1 Answers

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.

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!

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.

like image 54
gobernador Avatar answered Sep 28 '22 10:09

gobernador