/ W3SCHOOLS

W3schools - Package

이 페이지는 다음에 대한 공부 기록입니다
Lecture에서 배웠던 내용을 복습하며 작성했습니다

찾으시는 정보가 있으시다면
주제별reference를 이용하시거나
우측 상단에 있는 검색기능을 이용해주세요

Java Package & API

A package in Java is used to group related classes.

As a folder in a file directory.

Use packages to avoid name conflicts, and to write a better maintainable code.

Divided into two categories

  • Built-in Packages(from the Java API)

  • User-defined Packages

Built-in Packages

The Java API is a library of prewritten classes, included in the JDE

The library contains components for managing input, database programming, and more

The complete list can be found at Oracle

The library is divided into packages and classes

  • meaning can either import a single class(along with its methods and attributes), or a whole package that contain all the classes tha belong to the specified package

To use a class or a package from the library, need to use “import” keyword

import package.name.Class;
import package.name.*;

Import a class

import java.util.Scanner; //java.util is a package, while Scanner is a class of the java.util
class myClass{
	public static void main(String[] args){
		Scanner myObj = new Scanner(System.in); //create an object of the class and use any of the available methods found in the Scanner class documentation
		System.out.println(Enter username);
		String userName = myObj.nextLine();
		System.out.println(Username is :  + userName);
	}
}

Import a package

To import a whole package, end the sentence with an asterisk sign(*)

import java.util.*	//import all the classes in the java.util package

User-difined package

To create your own package, use the “package” keyword

package mypack;
class MypackageClass{
	public static void main(String[] args){
		System.out.println(This is my package!”);
	}
}

save the file as MypackageClass.java, and compile it

C:\Users\Your Name>javac MyPackageClass.java

Then, compile the package

C:\Users\Your Name>javac –d . MypackageClass.java
  • “-d” keyword specifies the destination for where to save the class file

  • You can use any directory name

  • if you want to keep the package within the same directory, use the dot(.)