Showing posts with label import. Show all posts
Showing posts with label import. Show all posts

Monday, 4 July 2011

Java package

Package Definition

A package is a collection of related classes.
It helps Organize your classes into a folder structure and make it easy to locate and use them.
More importantly,It helps improve re-usability.

Syntax:-
package <package_name>;

Package declaration

The first statement, other than comments, in a Java source file, must be the package declaration.
Following the optional package declaration, you can have import statements, which allow you to specify classes from other packages that can be referenced without qualifying them with their package.

Default package. Altho all Java classes are in a directory, it's possible to omit the package declaration. For small programs it's common to omit it, in which case Java creates what it calls a default package. Sun recommends that you do not use default packages.

Example of using package

Example1 : Creating the package:
package p1;
class c1{
public void m1(){
System.out.println("Method m1 of Class c1");
}
public static void main(String args[]){
c1 obj = new c1();
obj.m1();
}
}

Example 2 : Creating the sub packages:
package p1.p2;
class c2{

public void m2(){
System.out.println("Method m2 of Class c2");
}
public static void main(String args[]){
c2 obj = new c2();
obj.m2();
}
}


Compiling the above Classes

When a class is placed in a package the class file must be located in a sub-directory under one of the directories listed in the CLASSPATH. The sub-directory structure must map exactly onto the package name.
Given a CLASSPATH=/lib the above class must reside in one of:
./p1 
/lib/p1

Or  in case of example2 :
./p1/p2
or /lib/p1/p2

The javac compiler creates class files in the current directory by default, even if they are specified as belonging to a package. To get around this, use the -d flag to the compiler . Which will create the necessary directories under the /lib directory, if your classpath is /lib.

Take example1, Save the file as Demo.java.
Compile the file as,
javac – d . Demo.java
Run the code as
java p1.c1

Taking example2:
Save the file as Demo2.java.
Compile the file as
javac – d . Demo2.java

Run the code as
java p1.p2.c2

Importing a package


To create an object  of a class (bundled in a package), in your code, you have to use its fully qualified name.
Ex.
java.awt.event.actionListner object = new java.awt.event.actionListner();

But , it could become tedious to type in the long dot-separated package path name for every class you want to use. Instead it is recommended you use the import statement.

Syntax
import <package_name>;

Once imported , you can use the class without mentioning its fully qualified name.

import java.awt.event.*; // * signifies all classes in this package
import javax.swing.JFrame // here only the JFrame class is imported
//Usage
JFrame f = new JFrame; // without fully qualified name.

To import package

// Using packages created in earlier assignment
package p3;
import p1.*; //imports classes only in package p1 and NOT in the sub-package p2
&nbsp;
class c3{
public void m3(){
System.out.println("Method m3 of Class c3");
}
public static void main(String args[]){
c1 obj1 = new c1();
obj1.m1();
p1.p2.c2 obj2 = new p1.p2.c2();
obj2.m2();
}
}

Save the file as Demo2.java . Compile the file using the command
javac –d .Demo2.java

Execute the code using the command
java p3.c3

Packages - points to note:


  • To avoid naming conflicts packages are given names of the domain name of the company in reverse Ex :  com.guru99. com.microsoft, com.infosys etc.
  • When a package name is not specified , a class is into the default package (the current working directory) and the package itself is given no name. Hence you were able to execute assignments earlier.
  • While creating a package, care should be taken that the statement for creating  package must be written before any other import statements
  • When importing packages with * format, only classes in that packages are imported and not sub packages.

Wednesday, 13 April 2011

Static Imports in Java 5

Static keyword is used to allow access to an attribute/ a method or a class without creating instance of it. (Some of you may argue that this is not object oriented way, but we leave that discussion aside for now.) We use static for those elements which do not change from instance to instance of a class. An example would be constant variables in a program. These values are stored using ‘public static final’ keywords. In enum article we have seen one way of managing logically linked constants. Static import tries to improve the way we store and use static elements in program.
Java says it has tried to address an anti-pattern – using interface for constants. Some of us may have used this type of design in programs, where constants are grouped in an interface and used by implementing that interface. This approach is wrong because it alters the purpose of having interfaces in a Java application. Interfaces are used to define highest level of abstract behavior and also to expose a contract to the world in terms of method signatures. Thus, we cannot use interfaces to store constants. An alternative is having them in respective functional classes or in a separate class which can be reused.
When we use this class, we import it and use it wherever the variable is required. Here is the example.
Constants class
package constants;  

public class MyConstants {

public static final String CONSTANT1 = "constant 1";
public static final String CONSTANT2 = "constant 2";
public static final String CONSTANT3 = "constant 3";
}

 Class using constants without static import
import constants.MyConstants;  

public class WithoutStaticImport {

public static void main(String[] args) {
System.out.println(MyConstants.CONSTANT1);
}

}


 
If you have many such constants, then every time you need to use these constants with class name in front of it. With static import, you can get rid of the class name and use constants directly. Let us see how.

Using Static Constant

import static constants.MyConstants.CONSTANT1;  

public class WithStaticImport {

public static void main(String[] args) {
System.out.println(CONSTANT1);
}

}


Important Considerations:

  • Java suggests – use static imports sparingly because these reduce readability and maintainability of a program considerably.
  • Use it when you feel you are going to wrongly use inheritance (i.e. interfaces).
  • When number of variables is less and you can maintain the readability by using meaningful names.
Benefits of static import with already present static java fields
Here are some examples:
  • instead of System.out.println you can use out.println:
    Import the field:
    import static java.lang.System.out;

    So now in code you can write:
    out.println("Hello, World!");
  • PI instead of Math.PI
    area = PI * R * R
    look so much nicer than
    area = Math.PI * R * R