Packages
-
Grouping of related classes (e.g. subsystems).
-
Structuring big systems.
-
Provide access restrictions using:
public
,private
andprotected
modifier -
Resolving class name clashes. Example:
java.lang.String vs. my.personal.
String
-
Package names below java. are reserved.
-
Package names should not start with javax. either.
-
Package names must not contain operators:
mi.hdm-stuttgart.de
--> de.hdm_stuttgart.mi. -
Packages should start with reversed DNS avoiding clashes.
import
Bad | Good |
---|---|
import java.util.*; public class Q { public static void main(String[] args) { Scanner s = new Scanner(System.in); Date today = new Date(); } } |
import java.util.Scanner; import java.util.Date; public class Q { public static void main(String[] args) { Scanner s = new Scanner(System.in); Date today = new Date(); } } |
import java.lang.String; ❶ // Optional import java.util.Scanner;❷ // Required public class Q { public static void main(String[] args) { String message = "Hello!"; Scanner ❸ s = new Scanner(System.in); } }
❶ |
A class Print defined in package my.first.javapackage. |
❷ |
|
❶ |
Our project's start folder containing Java™ classes. |
❷ |
First package name component. |
❸ |
Second package name component. |
❹ |
Third package name component. |
❺ |
Class |