CH 08 Packages in JAVA
CH 08 Packages in JAVA
Packages
collection of classes and interfaces
provides a unique namespace for the classes.
declaration resides at the top of a Java source file.
Eliminates naming conflicts
Class that reside inside a package cannot be referred by their
own name alone.
The package name has to precede the name of the class of
which it is a part of.
All classes are part of some or the other package.
If the package keyword is not used in any class for mentioning
the name of the package, then it becomes part of the
default/unnamed package.
Package
Types of packages
mypack
main_class.java
class_name.java
Compiling and executing packages
compiling the class from our package
mypack>javac class_name.java
executing the class from main_folder
Set classpath
main_folder>set classpath =“.;\main_folder\mypack\”;
To compile main program
main_folder>javac main_class.java
To execute main program
\main_folder>java main_class
Wap to create user defined package with Student class and
display students information.
package studentpkg; import studentpkg.Student;
public class Student
import java.util.*;
{
public int rno; class PackageDemo
public String name; {
public static void main(String args[])
public Student(int r, String n)
{
{
rno=r; Student s1=new Student(101,"JOHN");
name=n; s1.display();
} }
public void display()
}
{
System.out.println("Roll No= "+rno);
System.out.println(“Name="+name); Output
} Roll No=101
} Name=JOHN
Compiling and executing package program
To compile class in user defined package
D:\div-a\studentpkg> javac Student.java
To set class path
D:\div-a>set classpath=“.;d:\div-a\studentpkg\”;
To compile main program
D:\div-a>javac PackageDemo.java
To execute main program
D:\div-a>java PackageDemo
Access protection
Access specifier use
Access Location
Non-subclasses in Yes No No No
other packages
Access Specifier Example
Suppose x & y are package
A is a public class within package x
B is another class within package x
C is subclass of A in package x
D is subclass of A within package y
E is class within package y
abc() is a method with default access in class A
xyz() is a method with protected access specifier in class A
pqr() is a method with public access specifier in class A
Access protection