Java p9
Java p9
Java p9
1. Introduction
What is package:-
Packages are used in Java, in-order to avoid name conflicts and to control access of class,
interface and enumeration etc. A package can be defined as a group of similar types of
classes, interface, enumeration or sub-package. Using package it becomes easier to locate
the related classes and it also provides a good structure for projects with hundreds of
classes and other files.
1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.
3) java.util: Contains utility classes which implement data structures like Linked
List, Dictionary and support ; for Date / Time operations.
5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
package pk1;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
Java Virtual Machine(JVM) uses classpath to locate the class files to execute the code.
If your classpath is not set and the class file is not present in the same directory as your
java file, then JVM will be unable to find the required class file, and it will throw an
error.
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
package pk1;
public class A
{
int a;
protected int b;
private int c;
public d;
A()
{
a= -1;
b= -1;
c =-1;
d = -1;
void msg(){
System.out.println(“Hellow this code is inside PK1.“);
}
}
}
B(){
System.out.println("value of a: " + a);
System.out.println("value of b: " + b);
// System.out.println(“value of c: “ + c); // error bcz c is private variable
System.out.println(“value of d: “ + d);
System.out.println(“value of e: “ + e);
System.out.println(“value of f: “ + f);
}
Output
• Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
• Default: The accesslevel of a default modifier is only within the package. It cannot
be accessed from outside the package. If you do not specify any access level, it will
be the default.
• Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
• Public: The access level of a public modifier is everywhere. It can be accessed from
within theclass, outside the class, within the package and outside the package.