In this programming language, a package defines a namespace in which classes are stored. A package is nothing but a directory. Generally, similar types of files are kept in a package. You can also create a hierarchy of packages, which means a package may contain sub-packages.
Packages are not only used for organizing files, it is also used for access control of member variables and methods as a package defines a namespace.
Classes in same package: How to run the Program?
A.java
B.java
TestMain.java
Classes in different package
A.java
B.java
TestMain.java
Naming Convention
Many developers are working on different projects in different companies or organizations. Sometimes, the developers are using some libraries that are developed by others. In this scenario, there is a high possibility of using the same name for different classes written by different developers. The same name of the classes results in a conflicting scenario when the classes are used in a project.
This problem can be resolved by using packages. If you need to use one of those classes in your class, you have to import the class by its name along with the package name. Thus, the names of the packages should be unique. Hence, the developer should follow the naming convention.
In this context, we will discuss how to define package names.
Only lowercase characters are used for package names to avoid conflict with the names of classes or interfaces.
Generally, reversed Internet domain name is used to begin their package names.
Name collisions that may occur within a single company can be handled by using the project name after the reversed domain name.
Note that in some cases, the internet domain name may not be a valid package name, if it contains a special character (other than a hyphen) or it begins with a digit.
Example
Let us discuss the previous example of the banking system.
Account.java
SavingsAccount.java
LoanAccount.java
HomeLoanAccount.java
EducationLoanAccount.java
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.