View RSS Feed

My Java Tips

using Packages

Rate this Entry
by , 11-09-2011 at 06:57 PM (591 Views)
Packages are used to group related classes, interfaces and enumerations together. Each package has its own namespace and provide access protection and name space management.


Using packages in your projects is a good programming approach. It makes more sense to use packages if you are working in a team on some big project.

Suppose you write a group of classes that represent vehicle objects like bus, truck and car. You also have interfaces called Drive and Stop and each of the vehicle will implement the interfaces to write its own functionality. In this scenario, bundling all these classes and interfaces into a package is a nice idea.

Following are the classes and interfaces we have for this example:

Java Code:
public class Car {

}

public class Bus {

}

public class Truck {

}

public interface Drive {

}

public interface Stop {

}
We will define a package and will place all these interfaces and classes into it. Lets name that package Vehicles, so each interface and class should have following statement at the start:

Java Code:
package Vehicles;

Now let say there is a default package and you have a class named MainClass. You want to make objects of Car class that reside in the package Vehicles. Here comes the visibility issue. Your default package cannot see the classes public classes defined in the package Vehicles until you import the package.

For instance: you want to make object of class car. Then there are two ways of doing that.


import Vehicles.Car;

Car obj = new Car();


Second way is :


...
Vehicles.Car obj = new Vehicles.Car();
..
Thing to note is, you cannot directly access private classes from a package, even it is imported into your class.

Submit "using Packages" to Facebook Submit "using Packages" to Digg Submit "using Packages" to del.icio.us Submit "using Packages" to StumbleUpon Submit "using Packages" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments