using Packages
15 November 2007Packages 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 functionalities. 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:
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:
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.
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: using Packages