- A library comprises a group of related files
eg: a math library will contain functions or subroutines that are used in mathematical calculations
- The basic idea behind using a code library is to sort out files or functions based on their functionality
- Using these codes saves a lot of coding time
eg. In C they are known as header files, in C++ as class libraries and in Java as packages or in C# is known as namespace.
|
Creating packages in Java |
- In Java, a package is a combination of classes, interfaces and sub-packages.
- For eg: java.awt package has a sub-package called java.awt.event
- These packages provides the set of classes , interface and method for the programmer to develop an application in an easier way sothat programmer can reuse everything from the package and save effort
Some more examples of built in packages
- java.lang
- java.io
- java.sql
- java.awt
- java.net
A package in Java can be created by including a package statement as the first statement in a Java program
Syntax to define a package is
package pkgname;
When a Java program is executed, the JVM searches for the classes used within the program on the file system.
Uses one of the elements to find a class
- The package name
- The directories listed in the CLASSPATH environment variable
- If no CLASSPATH is defined, then JVM looks for the default java\lib directory and the current working directory.
- it can also look into the \lib\ext folder, if you have made some api and then kept as jar file.
|
Executing class with package |
|
Executing class with package from different location |
|
Executing class if it is in package and available in jar file |
These are the Three Files available in MyJar Folder in C: drive.
Running Jar File from Command Prompt.
|
Packages and access control |
- A public member of a class can be accessed from anywhere;
- within the package, outside the package, within a subclass, as well as within a non-subclass.
- A member of a class that is declared private can be accessed only within the class but no where outside the class.
- If no access specifier is given, the member would be accessible within any class in the same package but not outside the package
|
Private |
No Modifier |
Protected |
Public |
Same class |
Yes |
Yes |
Yes |
Yes |
Same package Subclass |
No |
Yes |
Yes |
Yes |
Same package Non-subclass |
No |
Yes |
Yes |
Yes |
Diff package subclass |
No |
No |
Yes |
Yes |
Diff package Non-subclass |
No |
No |
No |
Yes |
|
Access Specifiers within a package among different classes |
|
Access Specifiers with different class in diff package |
- Logical grouping of classes and interfaces
- Avoiding name clashes
- Provides an extra level of protection to its members
Recent Comments