Day 25 : Package

Chi-Tse Chiang
2022-10-10 23:58:47

Intro

Up to now, we have introduced a lot of object-oriented concepts and implementations.

Today, we will introduce a ready-made tool that is very convenient to use in Java (or other programs)packages.

There are two types of packages:

1. Packages in the library
This package is already defined in the Java API, in short, it is in the Java library.

The library is further divided into single categories and entire packages

Take the file system as an example, it is a folder (API) with different files (classes) and folders (packages)

2. Customized package
The user can customize the content of the package and specify where it is stored.

When we want to use a package, we must use the keyword import at the beginning of the program to import the members in the library.

import java.util.Scanner;  //Import a class(Scanner)
import java.util.*;     //Import a package(java.util)

Scanner是java.util套件中的一個類別，import套件同時，也能使用裡面之類別

Package Lib

Import Class

We call the Scanner class in the java.util package in the library to read the contents from the user input.

import java.util.Scanner;

public class Main{
	public static void main(String[] args){
		Scanner new_obj = new Scanner(System.in);
		int[] grade={0,0,0};
		int count = 1;

		while(count <= 3){
			System.out.println("Student " + count + " grade: ");
			grade[ count-1 ] = new_obj.nextInt();
		}
	}
}

Import Package

To import the entire package, we must change to java.util .*

import java.util.*;

public class Main{
	public static void main(String[] args){
		Scanner new_obj = new Scanner(System.in);
		int[] grade={0,0,0};
		int count = 1;

		while(count <= 3){
			System.out.println("Student " + count + " grade: ");
			grade[ count-1 ] = new_obj.nextInt();
		}
	}
}

As mentioned above, the same code is used, but this part directly uses the package to summarize all tools.

Self-Declaration of Package

There are two things to note about self-declared packages:

1. How the package is declared

package package_name;

class package_class{
	/***************
   **description**
	****************/
}

package greeting;

class greetingClass{
	public static void main(String[] args) {
    System.out.println("Hello World!!!");
}

2. Storage location for the kit
After we have successfully created an object, we need to set its storage location.

First set the file address.

Category tool in the editing suite

! Note this step!
Here we specify the location where it will be stored. The keyword -d is used together with the address (C:, D:)
If you want to put the package in the same file location, just add . after -d.

import