Professional Documents
Culture Documents
KCS-602 LECTURE04 Package CSE
KCS-602 LECTURE04 Package CSE
Java packages
• Package: A collection of related classes.
• Can also "CONTAIN" sub-packages.
• Sub-packages can have similar names,
but are not actually contained inside.
• java.awt does not contain java.awt.event
package myPackage;
public class ClassA {
// class body
public void display()
{
System.out.println("Hello, I am ClassA");
}
}
• C://……../JAVA_Code/myPpackage/ClassA.class
• C://……../JAVA_Code/ClassX.class
Using a Package
• Within the current directory (“JAVA_Codes”) store the
following code in a file named “ClassX.java”
import myPackage.ClassA;
import pack1.Teacher;
public class Professor extends Teacher
{
// body of Professor class
// It is able to inherit public and protected members,
// but not private or default members of Teacher class.
}
Member access modes in Java
• class Balance {
• private String name; Class Fin {
• private double bal;
• Balance(String n, double b) { }
• name = n;
• bal = b;
• }
• void show() {
• if(bal<0)
• System.out.print("--> ");
• System.out.println(name + ": $" + bal);
• }
• }
// A simple package class AccountBalance {
package MyPack; public static void main(String args[]) {
class Balance { Balance current[] = new Balance[3];
String name; current[0] = new Balance("K. J. Fielding", 123.23);
double bal; current[1] = new Balance("Will Tell", 157.02);
Balance(String n, double b) { current[2] = new Balance("Tom Jackson", -12.33);
name = n;
bal = b; for(int i=0; i<3; i++) current[i].show();
} }
void show() { }
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
• Call this file AccountBalance.java
• and put it in a directory called MyPack.
• Next, compile the file. Make sure that the resulting .class file is also
in the MyPack directory.
• Then, try executing the AccountBalance class, using the following
command line:
…\java MyPack.AccountBalance
Remember, you will need to be in the directory above MyPack when
you execute this command. (Alternatively, you can use one of the
other two options described in the preceding section to specify the
path MyPack.)
As explained, AccountBalance is now part of the package MyPack.
This means that it cannot be executed by itself. That is, you cannot use
this command line:
java AccountBalance
AccountBalance must be qualified with its package name