Do I have to use “package” term in every class?

前端 未结 4 646
耶瑟儿~
耶瑟儿~ 2020-12-15 06:49

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

4条回答
  •  鱼传尺愫
    2020-12-15 07:35

    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.

提交回复
热议问题