Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
21 views15 pages

Java Package Usage Guide

Uploaded by

pp6524878
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views15 pages

Java Package Usage Guide

Uploaded by

pp6524878
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 15

USING A PACKAGE

file named ClassA.java


package package1;
public class ClassA
{
public void displayA()
{
System.out.println(“class A”);
}
}
store the file classA.java inside a
directory named package1 in the current
directory
after compiling the file the resulting .class
file .
ClassA.class will be stored in the package1
directory.
file-PackageTest1.java
import package1.ClassA;
class PackageTest1
{
public static void main(String args[ ])
{
ClassA ob=new ClassA ();
ob.displayA();
}
}
in the command prompt type:
$javac ./package1/classA.java
$javac PackageTest1.java
$java PackageTest1
another class of package1
create a file ClassB.java
package package1;
public class ClassB
{
public void displayB()
{
System.out.println(“class B”);
}
}
1.Define the class and make it public.
2.Place the package statement
package package1;
3. Store this as ClassB.java under the
directory package1.
4.Compile the file ClassB.java
// a file named PackagePgm.java
import package1.*;
class PackagePgm
{
public static void main(String args[ ])
{
ClassA ob1=new ClassA ();
ClassB ob2=new ClassB ();
ob1.displayA();
ob2.displayB();
}
}
When we import multiple packages,two or
more packages may contain classes with
identical names
package pack1;
public class Teacher
{......}
public class Student
{......}
second package
package pack2;
public class Courses
{......}
public class Student
{......}
we may import and use these packages like:
import pack1.*;
import pack2.*;
Student student1; // create student object
In this case,both packages contain the class
Student.compiler cannot understand which
one to use and generates an error.
So use its fully qualified name, which
includes its full package hierarchy
import pack1.*;
import pack2.*;
pack2.Student student1; // create student
object of
package named pack2

You might also like