Packages in java
Java allows to a group class and organizes them into packages. Packages are very simple and useful mechanism to organize, easily locate files, reuse code, use libraries and also save time. In real life, there are situations when we can tray to create the class in the same name. This provides to namespace collisions. Packages also help to prevent that kind of problems.
How to use a package:
The class can use all of the classes from their package and all of the public class from packages that belong to other pancakes. To get access to the public class from other packages we can do it in two ways:
Call a full name: com.somePackage myClass = new com.somePackage();
However, it’s not a very practical way. Easier and much faster way is to use keyword: import
. This keyword allows for easier use of a class from another package.
Of course, we can import all class from the package by add *, for example:
Adding a class to the package:
To add class to package first we must to add package name on the beginning of source file, for example:
If we don’t add package name, a class will be placed in a default package. This package doesn’t have a name.
Part of the program that is listed bellow describes that HelloController.java
belongs to com.billingsystem.controller
. Therefore file HelloController.java
must be stored in com/billingsystem/controller
:
My site is free of ads and trackers. Was this post helpful to you? Why not
Disqus is great for comments/feedback but I had no idea it came with these gaudy ads.