Packages and Access Control
Packages
Creating
- Put the package name at the top of every file in this package
- Store the file in a folder that has the appropriate folder name
In IntelliJ:
-
File → New Package
-
Choose package name (i.e. “ug.joshh.animal”)
Adding (new) Java Files to a Package, in IntelliJ:
-
Right-click package name
-
Select New → Java Class
-
Name your class, and IntelliJ will automatically put it in the correct folder
Adding (old) Java Files to a Package, in IntelliJ:
-
Add “package [packagename]” to the top of the file.
-
Drag the .java file into the corresponding folder.
Default packages
Bad:
- code from the default package cannot be imported,
- possible to accidentally create classes with the same name under the default package
JAR files
Creating a JAR File (IntelliJ):
-
Go to File → Project Structure → Artifacts → JAR → “From modules with dependencies”
-
Click OK a couple of times
-
Click Build → Build Artifacts (this will create a JAR file in a folder called “Artifacts”)
-
Distribute this JAR file
Build Systems
Rather than importing a list of libraries, we can simply put the files into the appropriate place, and use “Build Systems”.
Access Control
Access is based only on static type.
Modifier | Class | Package | Subclass | World |
---|---|---|---|---|
public | Y | Y | Y | Y |
protected | Y | Y | Y | N |
(package protected) | Y | Y | N | N |
private | Y | N | N | N |