OOPM JAVA - Create user defined packages (parameterized constructor.)

 Experiment No. 06

Aim: Write a Package MCA which has one class Student. Accept student detail through parameterized constructor. Write display () method to display details. Create a main class which will use package and calculate total marks and percentage.

Objective: To create user defined packages and there use in real world.

Outcome: Students created packages for various problems used in real world 

Theory

Packages in Java is a mechanism to encapsulate a group of classes, interfaces and sub packages. Many implementations of Java use a hierarchical file system to manage source and class files. It is easy to organize class files into packages. All we need to do is put related class files in the same directory, give the directory a name that relates to the purpose of the classes, and add a line to the top of each class file that declares the package name, which is the same as the directory name where they reside.

In java there are already many predefined packages that we use while programming.

For example: java.lang, java.io, java.util etc.

However one of the most useful feature of java is that we can define our own packages


Advantages of using a package

  • Reusability: Reusability of code is one of the most important requirements in the software industry. Reusability saves time, effort and also ensures consistency. A class once developed can be reused by any number of programs wishing to incorporate the class in that particular program.
  • Easy to locate the files.
  • In real life situation there may arise scenarios where we need to define files of the same name. This may lead to “name-space collisions”. Packages are a way of avoiding “name-space collisions”.


Types of package:

packages

  • Built-in package: The already defined package like java.io.*, java.lang.* etc are known as built-in packages.
  •  User defined package: The package we create is called user-defined package.

 

Built-in Packages

These packages consist of a large number of classes which are a part of Java API.Some of the commonly used built-in packages are:

1) java.lang: Contains language support classes(e.g classed which defines primitive data types, math operations). This package is automatically imported.

2) java.io: Contains classed for supporting input / output operations.

3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support ; for Date / Time operations.

4) java.applet: Contains classes for creating Applets.

5) java.awt: Contain classes for implementing the components for graphical user interfaces (like button , ;menus etc).

6) java.net: Contain classes for supporting networking operations.


User defined package

Creating a Package

While creating a package, you should choose a name for the package and include a package statement along with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package.

The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.

If a package statement is not used then the class, interfaces, enumerations, and annotation types will be placed in the current default package.

To compile the Java programs with package statements, you have to use -d option as shown below: 

javac -d Destination_folder file_name.java


Then a folder with the given package name is created in the specified destination, and the compiled class files will be placed in that folder.

 

Defining a Package:


This statement should be used in the beginning of the program to include that program in that particular package.

package <package name>;

Use package keyword

Is very first statement in JAVA program

    package pkg_name; 

if you want to create sub-packages

package rootPackage.subPackage1;

Must have exactly one public class

If you want more than one public class in same package then create different files for each public class.

Save JAVA program with public class class_name

. public class class_name { 

        }

 

Example

Let us look at an example that creates a package called animals. It is a good practice to use names of packages with lower case letters to avoid any conflicts with the names of classes and interfaces.

Following package example contains interface named animals −


package animals;

interface Animal {

   public void eat();

   public void travel();

}

Now, let us implement the above interface in the same package animals 

 

package animals;

/* File name : MammalInt.java */

public class MammalInt implements Animal {

   public void eat() {

      System.out.println("Mammal eats");

   }

   public void travel() {

      System.out.println("Mammal travels");

   } 

   public int noOfLegs() {

      return 0;

   }

 

   public static void main(String args[]) {

      MammalInt m = new MammalInt();

      m.eat();

      m.travel();

   }


Now compile the java files as shown below −

 

$ javac -d . Animal.java 

$ javac -d . MammalInt.java

 

Now a package/folder with the name animals will be created in the current directory and these class files will be placed in it.

 

You can execute the class file within the package and get the result as shown below.

Mammal eats

Mammal travels

 

The import Keyword

If a class wants to use another class in the same package, the package name need not be used. Classes in the same package find each other without any special syntax.


Algorithm:-

1. Start

2. create package MCA.

3. Define class Student with its attributes, parameterized constructor and methods in package MCA.

4. Create a main program with class name package_Demo

5. Import MCA to main program

6. Create object of Student class inside main class.

7. Invoke display() method of Student class on that object to display total marks and percentage.

8. stop


Code:- 

//Student.java

package mca;

public class Student

{

     public int r_no;

     public String name;

     public int a,b,c;

     int sum=0;

     public Student(int roll, String nm, int m1,int m2,int m3)

     {

          r_no = roll;

          name = nm;

          a = m1;

          b = m2;

          c = m3;

          sum = a+b+c;

     }

     public void display()

     {

          System.out.println("Roll_no : "+r_no);

          System.out.println("Name : "+name);

          System.out.println("-----MARKS-------");

          System.out.println("Sub 1 : "+a);

          System.out.println("Sub 2 : "+b);

          System.out.println("Sub 3 : "+c);

          System.out.println("Total : "+sum);

          System.out.println("percentage: "+sum/3);

          System.out.println("------------------");

     }

}

 

//StudentMain.java

import mca.Student;

import java.util.*;

import java.lang.*;

import java.io.*;

class StudentMain

{

     public static void main(String[] args)

     {

          String nm;

          int roll;

          Scanner sc = new Scanner(System.in);

          System.out.print("Enter Roll no:= ");

          roll = sc.nextInt();

          System.out.print("Enter Name:= ");

          nm = sc.next();

          int m1,m2,m3;

          System.out.print("Enter 3 sub mark:= ");

          m1 = sc.nextInt();

          m2 = sc.nextInt();

          m3 = sc.nextInt();

          Student s = new Student( roll,nm,m1,m2,m3);

          s.display();

     }

}


Output:- 

Create user defined packages (parameterized constructor.)

(For compiling this use notepad and command prompt on windows.)


Observations and learning:

  • We created a package MCA and it is use the display the student details .
  • In MCA package we have one student class.
  • This package i.e MCA package is used by the packagedemo class.
  • A class once developed can be reused by any number of programs by using packages.


Conclusion:

Packages can be considered as data encapsulation.By using package we can solve any given problem. It is Easy to locate the files with the help of packages.


Question of Curiosity

1. What are packages ? what is use of packages?

Answer :

Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. • Preventing naming conflicts. For example there can be two classes with name Employee in two packages, college.staff.cse.Employee and college.staff.ee.Employee

• Making searching/locating and usage of classes, interfaces, enumerations and annotations easier

• Providing controlled access: protected and default have package level access control. A protected member is accessible by classes in the same package and its subclasses. A default member (without any access specifier) is accessible by classes in the same package only. • Packages can be considered as data encapsulation (or data-hiding).


2. What is difference between importing "java.applet.Applet" and "java.applet.* "?

Answer : java.applet.Applet" will import only the class Applet from the package java.applet whereas "java.applet.* " will import all the classes from the java.applet package.


3. Which package is always imported by default?

Answer -The java. lang package is always imported by default. It is by default loaded internally by the JVM.


4. Can I import same package/class twice? Will the JVM load the package twice at runtime?

Answer :One can import the same package or same class multiple times. Neither compiler nor JVM complains about it. And the JVM will internally load the class only once no matter how many times you import the same.


5. Does importing a package imports the sub packages as well? E.g. Does importing com.bob.* also import com.bob.code.*?

Answer : No .Sub-packages need to be imported explicitly .


6. Explain the usage of Java packages.

Answer :In Java packages are for organizing our classes and interfaces .There are two types of packages- built in and user defined.


7. Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.BOB compile?

Answer -Yes the imports are checked for the semantic validity at compile time. The code containing the above line of import will not compile. It will throw an error saying, cannot resolve the symbol.


Name few classes that are part of java.io package ?

Answer :

Few such classes are :-

· BufferedInputStream

· BufferedOutputStream

· BufferedReader

· BufferedWriter

· ByteArrayInputStream

· ByteArrayOutputStream

· CharArrayReader

· CharArrayWriter – Set1 Set2

· Console

· DataInputStream – Set1 Set2

· DataOutputStream


Comments