Java Package Class Path and Access protection

How to Set the Class Path:

The classpath is a user defined environment variable that is used by Java to determine where predefined classes are located. It tells the java tools and applications where to find user-defined classes. The syntax to set the classpath is shown as:

C:> set CLASSPATH=%classpath%;classpath1;classpath2.....

You can set multiple path entries that are separated by semi-colons.
To make this thing more understandable, let's put the "HelloWorld" class along with its package "mypackage" under the "C:\mainpackage" directory. Thus the directory structure for this package is shown as:




Now we have changed the location of the package from C:\mypackage\HelloWorld.java to C:\mainpackage\mypackage\HelloWorld.java. Then the CLASSPATH  needs to be changed to point the new location of the package mypackage accordingly shown as:

set CLASSPATH = .;C:\mainpackage;

Although in such condition, Java will look for java classes from the current directory instead of the "C:\mainpackage" directory.


Access protection in packages:

 Access protection  Discription
 No modifier (default)  The classes and members specified in the same package are accessible to
all the classes inside the same package.
 public  The classes, methods and member variables under this specifier can be accessed from anywhere.
 protected  The classes, methods and member variables under this modifier are accessible by all subclasses,
and accessible by code in same package.
 private  The methods and member variables are accessible only inside the class.


Access to fields in Java at a Glance:

Access By public protected default private
The class itself Yes Yes Yes Yes
A subclass in same package Yes Yes Yes No
Non sub-class in the same package Yes Yes Yes No
A subclass in other package Yes Yes No No
Non subclass in other package Yes No No No

0 comments:

Post a Comment

 

learn java programming Copyright © 2011-2012 | Powered by appsackel.org