Program to create user-defined package named "p1" and put class "A" in it

package can be defined as a group of similar types of classes, interface, enumeration and sub-package. Package are used in Java, in-order to avoid name conflicts and to control access of class, interface and enumeration etc. Using package it becomes easier to locate the related classes.
Package in java can be categorized in two form,
  • Built-in package : Existing Java package for example java.lang, java.util, java.awt, etc
  • User-defined package : Java package created by user to categorized classes and interfaces.
  • .

Creating a package in java is quite easy. Simply include a package command followed by name of the package as the first statement in java source file.
package mypackage;

public class MyClass 

The above statement create a package called mypackage. Java uses file system directory to store package. For example the .class for any classes you define to be part of mypackage package must be stored in a directory called mypackage.

package p1;
public class A
 public void dispA()
  System.out.println("Inside from class A");

To compile the above package program use the following command.
javac  -d  .

After successful compilation the mypackage directory will be created and the .class file is placed in that directory. The output of this program is the .class file.

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative