Object Oriented Programming: Unit II: Inheritance, Packages and Interfaces

Packages

Purpose, Definition, Importance, Creating, Accessing, Importing, Example Java Programs

In Java, packages are used to achieve the code reusability. That means, the classes from other programs can be easily used by a class without physically copying it to current location.

Packages

Defining Package

• Purpose; In Java, packages are used to achieve the code reusability. That means, the classes from other programs can be easily used by a class without physically copying it to current location.

Definition; Package is a mechanism in which variety of classes and interfaces can be grouped together.

Importance: Following are the benefits of organizing classes into packages-

1. The classes defined in the packages of other program can be easily reused.

2. Two classes from two different packages can have the same name. By using the package name the particular class can be referred.

3. Packages provide the complete separation between the two phases- design and coding. In the design phase, we can design the classes and decide their relationship and then during the coding phase we can develop the Java code for corresponding classes and can group them in several packages according to their relationship with each other.

4. Using packages it is possible to hide the classes. This feature prevents other programs to access the classes that are developed for internal purpose only.

• Creating a package is very simple. Just include the command package at the beginning of the program. The syntax for declaring the package is

package name_of_package

• This package statement defines the name space in which the classes are stored. If we omit the package then the default classes are put in the package that has no name.

• Basically Java creates a directory and the name of this directory becomes the package name. For example - In your program, if you declare the package as -

package My Package;

then we must create the directory name My_Package in the current working directory and the required classes must be stored in that directory. Note that the name of the package and the name of the directory must be the same. This name is case sensitive.

• We can create hierarchy of packages. For instance if you save the required class files in the subfolder MyPkg3 and the path for this subfolder is C:\MyPkg1\MyPkg2\MyPkg3 then the declaration for the package in your java program will be -

package MyPkg1.MyPkg2.MyPkg3;

Creating and Accessing Package

In this section we discuss how to develop a program which makes use the classes from other package.

Step 1: Create a folder named My_Package.

Step 2: Create one class which contains two methods. We will store this class in a file named A.java. This file will be stored in a folder My Package. The code for this class will be as follows-

Java Program[A.java]

package My Package; //include this package at the beginning

public class A

{

int a;

public void set_val(int n)

{

a=n;

}

public void display()

{

System.out.println("The value of a is: "+a);

}

}

Note that this class contains two methods namely- set_val and display. By the set_val method we can assign some value to a variable. The display function displays this stored value.

Step 3: Now we will write another java program named PackageDemo.java .This program will use the methods defined in class A. This source file is also stored in the subdirectory My Package. The java code for this file is -

Java Program[PackageDemo.java]

import My Package.A; //The java class A is referenced here by import statement

class Package Demo

{

public static void main(String args[]) throws NoClassDefFoundError

{

A obj=new A(); //creating an object of class A

obj.set_val(10); //Using the object of class A, the methods present

obj.display(); //in class A are accessed

}

}

Step 4: Now, open the command prompt and issue the following commands in order to run the package programs

D:\>set CLASSPATH .;D:\;

D:\>cd My Package

D:\My_Package>javac A.java

D:\My_Package>javac PackageDemo.java

D:\My_Package>java Package Demo

The value of a is: 10

D:\My_Package>

CLASSPATH

The packages are nothing but the directories. For locating the specified package the java run time system makes use of current working directory as its starting point. Thus if the required packages is in the current working directory then it will found. Otherwise you can specify the directory path setting the CLASSPATH statement. For instance- if the package name My Package is present at prompt D:\> then we can specify

set CLASSPATH=.;D:\;

D:\>cd My Package

D:\My_Package\> Now you can execute the required class files from this location

Importing Package

• All the standard classes in Java are stored in named packages.

• There is no standard class present in Java which is unnamed. But it is always complicated to write the class name using a long sequence of packages containing dot operator. Hence the import statement is needed.

• The import statement can be written at the beginning of the Java program, using the keyword import.

• There are two ways of accessing the classes stored in the core package.

1. Method 1: We import the java package class using the keyword import. Suppose we want to use the Data class stored in the java.util package then we can write the import statement at the beginning of the program. It is as follows -

2. Method 2: There are some situations in which we want to make use of several classes stored. in a package. Then we can write it as

import java.util.*

Here* means any class in the corresponding package.

Ex. 2.15.1 Write a java program to maintain the books details like Bookld, accession number; book name, author, publication in books package and keep the journal details such as journal Id; journal name; in journal package in main class use these two packages details for staff and student classes and display the books and journals information as requested by the user.

Sol.:

Step 1: Create a folder named MyLibrary and save following two Java programs namely books.java and journals.java within it.

books.java

package MyLibrary;

import java.io.*;

public class books

{

int BookId, AccessionNumber;

String BookName, Author, Publication;

DataInputStream input=new DataInputStream(System.in);

public void ReadData()

{

Try

{

System.out.println("Enter BookId: ");

BookId= Integer.parseInt(input.readLine());

System.out.println("Enter Accession Number: ");

Accession Number=Integer.parseInt(input.readLine());

System.out.println("Enter Book Name: ");

BookName=input.readLine();

System.out.println("Enter Author Name: ");

Author=input.readLine();

System.out.println("Enter Publication: ");

Publication=input.readLine();

}

catch (Exception e)

{

System.out.println("You have entered wrong data!!!");

}

}

public void Display()

{

System.out.println("BookId: "+BookId);

System.out.println("Accession Number: "+Accession Number);

System.out.println("Book Name: "+BookName);

System.out.println("Author Name: "+Author);

System.out.println("Publication: "+Publication);

}

}

journals.java

package MyLibrary;

import java.io.*;

public class journals

{

int JournalId;

String JournalName;

DataInputStream input=new DataInputStream(System.in);

public void ReadData()

{

try

{

System.out.println("Enter Journal Id: ");

JournalId=Integer.parseInt(input.readLine());

System.out.println("Enter Journal Name: ");

JournalName=input.readLine();

}

catch(Exception e)

{

System.out.println("You have entered wrong data!!!");

}

}

public void Display()

{

System.out.println("Journal Id: "+JournalId);

System.out.println("Journal Name: "+JournalName);

}

}

Step 2: Compile the above two programs using following javac command

D:\MyLibrary>javac books.java

D:\MyLibrary>javac journals.java

Due to above commands the books.class and journals.java get generated within the folder MyLibrary/

Step 3: Come out of MyLibrary directory and create following program -

MainClass.java

import MyLibrary.*;

import java.io.*;

class Staff {

int StaffId;

String StaffName;

String Department;

DataInputStream input=new DataInputStream(System.in);

void ReadData()

{

try

{

System.out.println("Enter Staff Id");

StaffId= Integer.parseInt(input.readLine());

System.out.println("Enter Staff Name");

StaffName= input.readLine();

System.out.println("Enter Department of Staff");

Department input.readLine();

}

catch(Exception e)

{

System.out.println("You have entered wrong data!!!");

}

}

void Display()

{

System.out.println("Staff Id: "+StaffId);

System.out.println("Staff Name: "+StaffName);

System.out.println("Department: "+Department);

}

}

class Student {

int RollNumber;

String StudentName;

DataInputStream input=new DataInputStream(System.in);

void ReadData()

{

try

{

System.out.println("Enter Student Roll Number");

RollNumber= Integer.parseInt(input.readLine());

System.out.println("Enter Student Name");

StudentName= input.readLine();

}

catch(Exception e)

{

System.out.println("You have entered wrong data!!!");

}

}

void Display()

{

System.out.println("Student Roll Number: "+RollNumber);

System.out.println("Student Name: "+StudentName);

}

}

public class MainClass

{

public static void main(String[] args)throws IOException

{

Staff Staff_obj = new Staff();

Student Student_obj = new Student();

books Book_obj=new books();

journals journals_obj=new journals();

int choice;

char ans;

DataInputStream input=new DataInputStream(System.in);

do

{

System.out.println("Enter your choice: ");

System.out.print("\n 1.Staff \n 2.Student");

choice= Integer.parseInt(input.readLine());

switch (choice)

{

case 1:System.out.println("\n\t Enter The data for Staff...");

Staff_obj.ReadData();

Book_obj.ReadData();

journals_obj.ReadData();

System.out.println("\n\t Displaying Record...");

Staff_obj.Display();

Book_obj.Display();

journals_obj.Display();

break;

case 2:System.out.println("\n\t Enter The data for Student...");

Student_obj.ReadData();

Book_obj.ReadData();

journals_obj.ReadData();

System.out.println("\n\t Displaying Record...");

Student_obj.Display();

Book_obj.Display();

journals_obj.Display();

break;

}

System.out.println("\n Do you want to continue?");

String s1=input.readLine();

ans=s1.charAt(0);

}while(ans=='y');

}

}

Step 3: Execute above program using the following command

D:\>javac MainClass.java

D:\>java MainClass

Enter your choice:

1.Staff

2.Student

1

Enter The data for Staff...

Enter Staff Id

1

Enter Staff Name

Archana

Enter Department of Staff

Computer

Enter BookId:

101

Enter Accession Number:

1010

Enter Book Name:

Software Engineering

Enter Author Name:

Puntambekar

Enter Publication:

Technical

Enter Journal Id:

5001

Enter Journal Name:

IEEE

Displaying Record...

Staff Id: 1

Staff Name: Archana

Department: Computer

BookId: 101

Accession Number: 1010

Book Name: Software Engineering

Author Name: Puntambekar

Publication: Technical

Journal Id: 5001

Journal Name: IEEE

Do you want to continue?

n

Review Questions

1.Give a brief overview of java packages. Write necessary code snippets.

2.What are packages? Explain how will you import a package in Java. Give example.

3.What is meant by package? How it is created and implemented in JAVA.

4.With suitable examples explain how packages can be created, imported and used. Also elaborate on its scope.

Object Oriented Programming: Unit II: Inheritance, Packages and Interfaces : Tag: : Purpose, Definition, Importance, Creating, Accessing, Importing, Example Java Programs - Packages