[Read more…] about ListIterator Java Example
SAXParser Example in Java
xml parsers Java Example
Adding Classes From A Package to Your Program
The packages are used for categorization of the same type of classes and interface in a single unit. There is no core or in-built classes that belong to unnamed default package. To use any classes or interface in other class, we need to use it with their fully qualified type name. But some time, we’ve the need to use all or not all the classes or interface of a package then it’s a tedious job to use in such a way discussed. Java supports imports statement to bring entire package, or certain classes into visibility. It provides flexibility to the programmer to save a lot of time just by importing the classes in his/her program, instead of rewriting them.
In a Java source file, import statements occur immediately following the package statement (if it exists) and must be before of any class definitions. This is the general form is as follows:
import pkg1 (.pkg2). [classname|*l;
For example
import java.util.Vector;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
The star (*) increases the compilation time, if the package size is very large. A good programming methodology says that give the fully qualified type name explicitly, i.e. import only those classes or interface that you want to use instead of importing whole packages. Yet the start will not increase the overhead on run-time performance of code or size of classes.
Example:
//Student.java
package student;
class Student
{
private int rollno;
private String name;
private String address;
public Student(int rno, String sname, String sadd}
{
rollno = rno;
name = sname;
address = sadd;
}
public void show()
{
System.out.println(“Roll No :: ” + rollno);
System.out.println(“Name :: ” + name);
System.out.println(“Address :: ” + address);
}
}
// Test.java
package student;
class Test extends Student
{
protected int marksSubjecti;
protected int marksSubject2;
protected int marksSubject3;
protected int marksSubject4;
public Test(int rno, String sname, String sadd,int mi, int m2, int m3, int m4)
{
super(rno,sname,sadd);
marksSubjecti = mi;
marksSubject2 = m2;
marksSubject3 = m3;
marksSubject4 = m4;
}
public void show()
{
super.show();
System.out.println(“Marks of Subject1 :: ” + marksSubject1);
System.out.println(“Marks of Subject2 :: ” + marksSubject2);
System.out.println(“Marks of Subject3 :: ” + marksSubject3);
System.out.println(“Marks of Subject4 :: ” + marksSubject4);
}
}
//Result.java
package student;
public class Result ex..tends Test
{
private int totalMarks;
private float percentage;
private char grade;
public Result(int rno, String sname, String sadd,int mi, int m2, int m3, int m4)
{
super(rno,sname,sadd,ml,m2,m3,m4);
totalMarks = marksSubject1 + marksSubject2 + marksSubject3 + marksSubject4;
percentage = (totalMarks*100.00F/600.00F);
if (percentage >=50.00F)
grade=’D’;
else
if(percentage >=55.00F && percentage<=60.00F)
grade = ‘C’;
else
if (percentage >=6l.00F && percentage<=70.00F)
grade = ‘B’;
else
if(percentage >=7l.00F && percentage<=75.00F)
grade = ‘A’;
else
if (percentage >=76.00F && percentage<=85.00F)
grade = ‘H’;
else
grade = ‘S’;
}
public void show()
{
super.show();
System.out.println(“Total Marks :: ” + totalMarks);
System.out.println(“Percentage :: ” + percentage);
System.out.println(“Grade :: ” + grade);
}
}
//ImportPackageDemo.java
import student.Result;
public class ImportPackageDemo
{
public static void main(String ar[])
{
Result ob = new Result (1001, “Alice”, “New York”,135,130,132,138);
ob.show ();
}
}
In the source file ImportPackageDemo, import student. Result is the first statement; it will import the class Result from the student package.
Access Protection in Packages
Access modifiers define the scope of the class and its members (data and methods). For example, private members are accessible within the same class members (methods). Java provides many levels of security that provides the visibility of members (variables and methods) within the classes, subclasses, and packages. [Read more…] about Access Protection in Packages
What is Packages in Java ? with Example
One of the critical aims of Java and other object-oriented programming languages is that reusable classes should be created and made available to programmers so that the same code is not written repeatedly by different people. We reused the classes within a program by extending the classes and implementing the interfaces. Moreover, most of the classes that we created so far did not interact much with the outside world as they were almost self-contained, except that some of them referred to Java classes such as String from java.lang package and Scanner from java.util.lang package. However, while designing most of the real world applications, the developers write code in the form of Java classes, which eventually needs to be brought together to work as a single application.
When more than one programmer writes a more extensive application, several problems may arise such as
• There may be naming conflicts, i.e., the same class name may be given by different programmers while designing classes.
• Difficult to find the classes that are related in some way but scattered in different files/ folders.
• Cannot restrict access to your classes.
These problems can be solved using the concept of packages.
Packages In Java
A package is a collection of related classes that provides a convenient mechanism for managing a broad set of classes and prevents class name conflicts. The classes in the package are grouped by purpose or by an application. It enables you to keep your classes separated from the classes in the Java API, allow you to reuse your classes in other applications and even let you distribute your classes to others.
Java platform includes several packages that group classes according to their functionality. For example, Input/Output classes are in java. io package, utility classes in java.util package, applet classes in java.applet and so on. Each standard package name begins with java, javax, etc.
In Java, every class contained in a package including those that you have defined so far in the various programming examples. However, you never referred to any package explicitly while creating your classes. It is because you have been implicitly using the default package to hold your classes, and this does not have a name. Any class in a single directory on your hard disk that does not specify a package name are part of the default package. Using the unnamed package is acceptable for small projects, but in most cases, it is better to organize classes into named packages to provide better encapsulation.
Packages can not only contain classes but may also contain other packages. Each subpackage usually represents a smaller more specific group of classes. Packages arranged hierarchically. Each subpackage is separated from a package above it by a period (.) which indicates this subpackage is one level below the package defined above it. For example, java.util.Scanner specifies that Scanner is a class in the package util and util is a package in the package java.
The package java.util indicates that the package java is at the first level. The subpackage util which is separated by a dot from is java one level below it. Moving each level down, we get more specific information about classes. So the java.util package contains utility classes.
The JDK relies on the computer hierarchical file system to manage packages. It organizes its vast collection of classes into a tree-like hierarchy of packages within packages which is equivalent to directories within directories. In other words, Java expects one to one mapping of the package name and file system directory structure. For example, in the package java. uti!, each part separated by a period (.), i.e., java and util, each correspond to a directory. The first directory is the java directory and within this directory is the subdirectory util. So the path corresponding to this package is java\util in the windows system.
Creating a Java Package
Creating a Java package is quite simple. You just need to follow the following steps.
1. Choose a package name: Naming a package is a crucial aspect of creating a package. The package name must be unique to prevent the problem of name conflicts. By convention, package names begin with a lowercase letter to distinguish them from the class names.
We shall shortly be creating a package named shapes3d which shall contain classes relating to three-dimensional shapes such as Sphere.java, Cuboid.java.
Often the companies that are involved in software development use their unique domain name to name their package — the elements in the domain name written in the reverse order to make it easier to read. For example, If the domain name of the company is ecomputernotes. com then it should place all their code into packages that have names beginning with com.ecomputernotes.
2. Pick up a base or root directory: After choosing the package name, the next step is to choose a base directory for your source tree. The base directory is the directory that contains the directories for your various packages. In our example, we use c: \javaprog as a base directory.
3. Make a subdirectory from the base directory that matches your package name: Since our package name is shapes3d so create a subdirectory named shapes3d in the base directory c:\javaprog.
4. Declaring package members: In this step, add a package declaration to the source file of each class that is part of the package. Placing a package declaration in the java source file indicates that the class declared in the file is the part of the specified package.
The package declaration must contain the keyword package followed by an identifier and a semicolon. For example, to create a package named sphere3d, use the following package declaration
package sphere3d;
The package declaration must be the first non-comment, a non-blank statement in the source file. There can be only one package statement per source file, so all classes in the source file must be in the same package.
In order to put the Sphere class in the shapes3d package, create the Sphere.java file as shown
// sphere class in shapes3d package
package shapes3d;
public class Sphere {
double radius;
public Sphere(double r){ radius = r;}
public double volume(){
return((4.0*Math.PI * radius * radius * radius)/3.0);
}
public double surfaceArea(){
return(4.0*Math.PI * radius * radius);
}
}
The Sphere class is declared public. If it is not declared public, it can only use by other classes in the same package. If you want to put several classes into the package, you have to create a separate source file for each of them because a file can have only one public class.
You can also create a hierarchy of packages. For this, you need to separate each package name from the one above it by use of a period (.). Its syntax is
package pack1.pack2 …. packN;
For example:
Package A.B; must be stored in base directory/A/B.
5. Place your source file into the package subdirectory: Once Sphere.java file has created; it is necessary to save it into the package subdirectory shapes3d. So the file Sphere.java the path
C:\javaprog\shapes3d\Sphere.java
6. Compile your source files – The next step is to compile the classes in the package as usual. So in our case, the class Sphere. java compiled using the following command.
C:\javaprog\shapes3d>javac Sphere.java
Similarly, follow the same steps for creating the Cuboid. java file and compile it.
//Cuboid class in shapes3d package
package shapes3d;
public class Cuboid {
double length , width , height;
public Cuboid(double l , double w , double h) {
length = l; width = w; height = h;
}
public double volume() {
return(length * width * height);
}
public double surfaceArea() {
return(2.0 * (length * width + width * height + height * length));
}
}
Now the file organization will look like,
COMPILING WITH -d(directory) FLAG
So far in our discussion, the source file and the class file were stored in the same directory. But quite often while working with projects, the source files and the class files are stored separately. In order to explain this, let us consider an example of the directory structure as shown in Fig.
From the Fig., we come to know that the source file Sphere.Java is stored in the directory path
C:\javaprog\source\shapes3d
Now if we want to store the class file Sphere.class that obtained on compiling the source file in the similar directory structure but under the classes directory then for this, you need to compile the file with -d flag. Compiling with -d flag tells the compiler not just to put your classes into the correct directory structure but also create the directories if they do not exist. The advantage of this approach is that we do not have to create the directories under the classes directory manually.
The command that helps to create the class file under the classes directory is as follows.
C:\javaprog>javac -d classes source\shapes3d\Sphere.java
After executing the above command in the classes directory, the directory shapes3d will be created which will contain Sphere.class file.