Packages and Access Modifiers

Packages

Think of the package you use when collecting garbage.
Java provides a package to manage classes with similar features and similar nature.
All of the Java APIs belong to a specific package (usually a package with names beginning with java).
Now let's look at how to make the class we want to create belong to a specific package.

BankAccount.java
package javabank;

public class BankAccount {
	private String accountNo;
	private long balance;
	
	public void deposit(long amount) {
		balance = balance + amount;
	}
	
	public void withdraw(long amount) {
		balance = balance - amount;
	}
	
	public long getBalance() {
		return balance;
	}
	
	public static void main(String[] args) {
		System.out.println("Package Test!");
	}
}

The first code, package javabank; makes the BankAccount class belong to the javabank package.
When you compile a Java source that declares a package, you must specify a directory after -d followed by a byte code.
If the -d option is omitted, the bytecode is not applied to the package.
Create the BankAccount.java source file in the C:\javaApp\bank\src\javabank directory.
package example directory
The bin directory is the directory where the bytecode is located.
The src directory is the directory where the Java source files are located.
If you declare the package, create a subdirectory with the package name in src and place the source there.
Most developers manage the source this way.

Package names are usually in reverse order of domain name.
Package names are usually in reverse order of domain name.
The package name preferably includes two or more dots.
If you have applied the net.java_school.commons package to the Log class, create the directory and place the source files as shown below.
javaApp-Log.java

Let's get back to BankAccount.java.
Go to C:\javaApp\bank\src\javabank and compile as below.

C:\ Command Prompt
C:\javaApp\bank\src\javabank>javac -d C:/javaApp/bank/bin BankAccount.java

The path separator following the -d option can also use the / (slash), even on Windows systems.
Of course, you can also use the path separator in the Windows system \ (backslash).
After compiling, go to the C:\java App\bank\bin directory and check whether the bytecode of BankAccount is created.

C:\ Command Prompt
C:\javaApp\bank\bin>dir
2008-03-07  12:06  PM    <DIR>          javabank

You will not see the BankAccount.class file in the bin directory, instead you will see the javabank directory.
The BankAccount.class file can be found in this javabank subdirectory.
When you compile BankAccont.java, if you specify the C:\javaApp\bank\bin directory with the -d option.
a subdirectory with the same name as the package name is created in the C:\javaApp\bank\bin directory.
BankAccount.class is created in the javabank directory.
Account.class and Account.java

The JVM understands that there is a javabank.BankAccount class in the C:\javaApp\bank\bin directory.
For a class that has a package applied, the fully qualified class name (FQCN) of the BankAccount class is javabank.BankAccount.
To use the BankAccount class in another class, you must write javabank.BankAccount in your code.
The same is true when you run classes.
To run the BankAccount class, you need to run java javabank.BankAccount in the C:\javaApp\javabank\bin directory.
This is because the JVM understands that there is a javabank.BankAccont class in the bin directory.

C:\ Command Prompt
C:\javaApp\bank\bin>java javabank.BankAccount
Package Test!

To run a class in a directory that does not have a class, you need to tell the JVM where the class is located.
The way to tell the JVM that the class is located is to use the Java interpreter's classpath1 option.
Below is running javabank.BankAccount in the C:\Program Files directory.

C:\ Command Prompt
C:\Program Files>java -classpath C:/javaApp/bank/bin javabank.BankAccount
Package Test!

-classpath followed by the path where the class is located.
In the above, classpath is an absolute path.
If the classpath is specified as a relative path, it is as follows.

C:\ Command Prompt
C:\Program Files>java -classpath ../javaApp/bank/bin javabank.BankAccount
Package Test!

. Is the current directory.
.. refers to the directory one level above.
The Java compiler javac.exe also has a classpath2 option.
The Java compiler uses this option if you have code that uses classes (bytecode) created by other users in the Java source you are trying to compile.
If the class (bytecode) created by another user is in C:\javaApp\commons\bin, you must tell the Java compiler this path.
This is because the Java compiler verifies that the bytecodes used by the source is being used properly.
I will make an example of the above explanation.
For example, we need to create a new class, so we have the following directory structure.
Log.class and Log.java

The following is a new class to create.

Log.java3
package net.java_school.commons;

public class Log {
	public static void out(String msg) {
		System.out.println(new java.util.Date() + " : " + msg);
	}	
}

Compile Log.java.

C:\ Command Prompt
C:\javaApp\commons\src\net\java_school\commons>javac -d ^
C:\javaApp\commons\bin Log.java

Next, modify the BankAccont class to use the Log class.
The FQCN of the Log class is net.java_school.commons.Log and should be written to the source as well.

public void deposit(long amount) {
	balance = balance + amount;
	net.java_school.commons.Log.out(amount + " dollars have been deposited.");
	net.java_school.commons.Log.out("Balance is $ " + this.getBalance());
}

public void withdraw(long amount) {
	balance = balance - amount;
	net.java_school.commons.Log.out(amount + " dollars have been withdrawn.");
	net.java_school.commons.Log.out("Balance is " + this.getBalance());
}

public static void main(String[] args) {
	BankAccount myAccount = new BankAccount();
	myAccount.deposit(10000);
	myAccount.withdraw(500);
}

Recompile BankAccount.java.

C:\ Command Prompt
C:\javaApp\bank\src\javabank>javac -d C:\javaApp\bank\bin ^
-classpath C:\javaApp\commons\bin Account.java

Run the javabank.BankAccount.

C:\ Command Prompt
C:\javaApp\bank\bin>java -classpath .;C:\javaApp\commons\bin ^
javabank.Account

Our Java programs consist of two classes.
These are the javabank.Account and net.java_school.commons.Log classes.
Because these two classes are located differently, you need to specify the location of the two classes with the classpath option of the Java interpreter.
When the classpath option is used, the JVM looks only for classes where the classpath is set.
So the dot (.), Which means the current directory, is included in the classpath.

How to add an external Java library to your Java program

Most external Java classes are provided as jar-compressed files.
To deploy the Log class for use by other Java programmers, use jar.exe.
Execute the following command in the directory where Log bytecode is located.

C:\ Command Prompt
C:\javaApp\commons\bin>jar cvf java-school-commons.jar .

Using the explorer, cut the java-school-commons.jar file created in commons directory and paste it into C:\devLibs.
Run the javabank.Account class.
This time, use the Log class in the java-school-commons.jar file in C:\devLibs.

C:\ Command Prompt
C:\javaApp\bank\bin>java -classpath ^
.;C:\devLibs\java-school-commons.jar javabank.Account

The path to the java-school-commons.jar file must be specified in the classpath.

Access Modifiers

The access modifiers decide whether it is accessible from the outside.
The access modifiers provides a two-step access control.
Level 1 access control is when the accessor is used in the class declaration.

The public access modifier which used in the class declaration part of BankAccount

package javabank;

public class BankAccount {
	//...
} 

The package private access modifier which used in the class declaration part of BankAccount

package javabank;

class Account {
	//...
} 
Level 1 access control: when an access modifier is used in a class declaration
public It can be referenced in any package classes.
package private It can be referenced in same package classes.

Below is an example of referring to the javabank.BankAccount class in the example.BankSystem class.

package example;

public class BankSystem {

	//You can declare a parameter of type javabank.BankAccount.
	public void deposit(javabank.BankAccount account, long amount) {
		account.deposit(amount);//At this point, the access modifier used in the deposit() method declaration is applied.
	}

}

The following figure shows that all the classes in the javabank package have public access modifiers specified in the class declaration section.
(+ Stands for public) PUBLIC 접근자 그림
Suppose you have created a Bank, Customer with a javabank package like BankAccount.
Any class that belongs to any package can reference Bank, Customer, and BankAccount.
As shown in the figure, the BankSystem in the example package can refer to all classes in the javabank package.
As you can see from the BankSystem source, it means you can declare variables like javabank.BankAccount account.
You can use the import statement to reduce javabank.BankAccount to BankAccount in the class body.

package example;

import javabank.Account;

public class BankSystem {

	public void deposit(BankAccount account, long amount) {
		account.deposit(amount);
	}

}

Suppose you set a package private access modifier in the class declaration of Bank, Customer, and BankAccount.
package private diagram
In this case, the BankSystem class can not refer to Bank, Customer, or Account.
If you try to reference the Bank, Customer, and BankAccount classes in BankSystem, you get a compile error.

Step 2 Access Control: When an access modifier is used in a field or method declaration
public The field or method is accessible from all packages.
protected The field or method is only accessible from the same package.
In addition, if the packages of the subclass and the superclass are different, the subclasses can access protected fields and methods of the superclass.
package private The field or method is only accessible from the same package.
private It is not accessible from outside the class.

A field is a data structure declared in a class body.
It's easy to understand if you think everything is not a method in a class body.
A member is a variable that stores the property of an object or a method corresponding to an action of an object.
If public is applied to a field or method, it can be accessed from any package.
If the field or method is private, it can not be accessed from the outside.
The package private access modifier is only accessible from the same package.
The protected access modifier is more accessible than the package private access modifier.
For the protected access modifier, it's a good idea to review the description below after studying inheritance.
It can be accessed from the same package as the package private accessor.
In addition, protected members of the parent class can be accessed from child classes that differ in package from parent.
It should be noted that it is a protected member, not a protected field or method.
In the figure below, # means protected.
Protected 접근자 예 그림

Encapsulation: To access the data of an object, access it only through a method.

When designing a class, the following should be kept as it is the basis of object-oriented programming.
This is called encapsulation, which allows you to see only the essential parts of the object when viewed from the outside.

  1. Declare the member variable as private.
  2. Declare public setter and getter methods for private member variables

Let's encapsulate the member class of a website.

User.java
package net.java_school.user;

public class User {
	private String username;
	private String password;
	private String fullName;
	private String email;
	
	//getters and setters
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getFullName() {
		return FullName;
	}
	public void setFullName(String fullName) {
		FullName = fullName;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
}

Eclipse

Editors such as Notepad or Edit Plus will no longer be used.
All subsequent chapter examples will use Eclipse.
With Eclipse, you can manage your sources with the directory structure you have practiced above and you do not have to worry about the classpath when compiling.
Download the Eclipse IDE for Java EE Developers from http://www.eclipse.org/downloads/.
Unzip and copy the generated eclipse folder and paste it to the desired location.
Assume that you have pasted the eclipse folder into C:\.

Run

Run C:/eclipse/eclipse.exe to launch Eclipse.
Eclipse asks you where to specify your workspace.
workspace launcher
Workspaces contain and manage one or more projects.
Do not select the workspace as the default directory as shown above.
Also, do not check Use this as default and do not ask again.
It may be convenient to have multiple workspaces to manage projects of different characteristics.
In this example, the workspace is set to C:\javawork.
If you specify it and click the OK button, you can see the following welcome message.
welcome
For reference, this article summarizes the welcome page tutorial.
Closes the welcome page.
the following workbench appears.
workbench

Eclipse Terminology

Workbench

It refers to the entire window seen in Eclipse.
A window is divided into four areas, which are called views.

Perspective

Including all of the views is called a perspective.
The above screen is a Java perspective.
This perspective consists of the views needed to develop a Java program.
To change the perspective, use the Open Perspective menu bar button in the top right corner.

Package Explorer View

The top left view shows the resources (packages, classes, external libraries) belonging to the Java project.

Hierarchy View

The upper-left view shows Java's inheritance structure.

Outline View

The view at the top right shows the structure of the source file in the editor.

Editor View

It is used to edit the source code in the view located in the center of the screen.

Problems View

Show compilation errors or warnings at the bottom of the view.

Javadoc View

The view at the bottom shows the Java document for the selected part in the Package Explorer or Outline view.

Declaration View

The view at the bottom shows briefly how the selected part of the editor is declared.

You can change the position of the view to the desired position with the mouse.
But it is good to leave it until you get used to it.

Practice the Java example using Eclipse

Make sure it is a Java perspective.
In Eclipse, the Java source must belong to the project.
To create a Java project, select File - New - Java Project from the menu bar or click the leftmost button on the toolbar as shown below.
toolbar
Name the project HelloWorld.
Other settings do not have to be specified.
Eclipse is managed by storing the source in the src directory and the compiled binaries in the bin directory.
Click Finish and the HelloWorld project will be created and displayed in the Package Explorer.
project wizard
Click second on the toolbar menu below.
toolbar
Type net.java_school.example in the package name and click Finish.
You should now see the package in the Package Explorer view.
package wizard
With the mouse selected in the Package Explorer in the net.java_school.example package, click the last button on the right of the toolbar menu below.
toolbar
Enter HelloWorld as the class name.
Check the public static void main (String [] args), because the main method is required.
class wizard
Click on Finish and implement the main method in the editor as shown below.

HelloWorld.java
package net.java_school.example;

public class HelloWorld {

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

}

If you save, you do not have to compile.
This is because Eclipse continues to compile in the background.
Here's why you can see compilation errors right from the editor.
To run the class, right-click the HelloWorld class in the Package Explorer, open the context menu, and select it as shown below.
run
A console view is displayed and Hello World! console view


Comments
  1. When you run the Java interpreter (java), the class loader The classpath finds all the class information that makes up the Java program and loads it into the memory space.
    At this time, if it can not find even one class, it prints an error message that the execution fails and the class can not be found.
    If you do not specify the classpath option, the class loader looks for the class you created in the current directory.
    The path to the Java API, such as the java.lang.String class or the java.lang.System class, is already known by the class loader It is not specified in the classpath.
  2. The classpath option of javac or java can be replaced with the cp option.
  3. The out method of the Log class is a static method, and the description of the static keyword is covered in static.