Accessing of a package in Java

 Program that illustrates the Accessing of a package.


Assume you have the following directory structure:


myproject/

├── mypackage/

│   └── MyClass.java

└── TestPack.java


Here's the code for each file:


mypackage/MyClass.java (located in the mypackage package):


package mypackage;

public class MyClass 

{

  public void display() 

 {

    System.out.println("This is MyClass from mypackage.");

  }

}


//Main.java (located outside the mypackage package):


import mypackage.MyClass;

public class TestPack 

{

  public static void main(String[] args) 

  {

     MyClass myObject = new MyClass();

     myObject.display();

    }

}


To compile and run this program:


1) Open a terminal/command prompt and navigate to the myproject directory (the parent directory of mypackage and          Main.java).

2) Compile the MyClass.java file in the mypackage directory:


javac mypackage/MyClass.java


Compile the Main.java file in the parent directory:


javac TestPack.java


Run the program:


java TestPack


Output:


This is MyClass from mypackage.

Post a Comment

0 Comments