Saturday, 22 June 2013

What are packages in JAVA

Packages are nothing but folders containing similar java classes, interfaces, enumerations, annotations.
So if you have n java classes that are focused on one functionality, we generally store those classes in one folder. This is called as a package.

Advantages of creating packages in JAVA:-

  • We can easily search the classes, interfaces etc.
  • It helps in naming convention.
  • It prevents name conflicts.
If you have a package transport wich contains Bike class.
You can access class using below methods
  • Class name -> transport.Bike.java
  • Path name -> transport/Bike.java
Generally source/class files are stored in reverse company domain name.

for example - 

com\amazon\transport\Abc.java
com.amazon.transport\Abc.class

//ABC.java - source file

package com.amazon.transport; 
public class Abc{ }
class Xyz{ }

When you compile the Abc.java
$javac -d . Abc.java

This will create 2 class files.

com\amazon\transport\Abc.class
com\amazon\transport\Xyz.class

To import all classes defined in package transport, you can use below statment

import com.amazon.transport.*


To tell JVM where it should find the classes, we can set the classpath variable giving the path your class files are stored.









No comments:

Post a Comment