Tuesday, April 29, 2014

Packages in java (Part 1/2)

This is the first article on packages. 

Simply put, a package is a folder that organizes related top-level classes and interfaces.

A package contains source code files (containing top-level classes and interfaces) and sub-packages with source code files of their own. 

Important points about packages:
  • The package statement should be the first line of code in a compilation unit.
  • There is only one package statement in each compilation unit.
  • The package java.lang.* is imported automatically in each .java file.
  • The containing package may be imported. Such an import is ignored.

//First line of code is package statement

package com.choosejava.blogspot;

//java.lang package is automatically imported

//May specify redundantly
import java.lang.*;
import somepackage.*;

//This line is ignored
import com.choosejava.blogspot.*;

//Top-level classes and interfaces
class A{...}
interface I1{...}

You cannot single-import a type with the same simple name as a top-level class or interface.

Also, 2 single-type import declarations should not attempt to import types with the same simple name. Following is invalid.

package somepackage;

import otherpackage.TestClass;

class TestClass{...}

//Reference to TestClass will be ambiguous

Following is also invalid:

import otherpackage.Vector;
import java.util.Vector;
//Reference to Vector class will be ambiguous


Duplicate import declarations are allowed.

Let's modify the above code with TestClass a little bit. 

Following is valid:

package somepackage;

import otherpackage.*;

class TestClass{...}

//Refer to otherpackage.TestClass using the fully qualified name

No comments :

Post a Comment