# Oracle/Sun Microsystems 建議的 Java 源代碼結構
[TOC]
###### tags: `java`
---
- 應由 blank line<SUP>(空行)</SUP>分隔 sections<SUP>(段落)</SUP>並為 sections<SUP>(段落)</SUP>加上 comments<SUP>(註解)</SUP>。
- 盡量避免超過 2000 行。
:::info
每個 Java 源代碼檔案都包含一個 `public class` 或 `public interface`,當有 `private class` 或 `private interface` 時可將它(們)放在與 `public class` 同一個 Java 源代碼檔案中。
:::
## 檔首註解
All source files should begin with a c-style comment that lists the class name, version information, date, and copyright notice:
```java
/*
* Classname
*
* Version information
*
* Date
*
* Copyright notice
*/
```
## Package and Import Statements
The first non-comment line of most Java source files is a package statement. After that, import statements can follow.
```java
package java.awt;
import java.awt.peer.CanvasPeer;
```
## Class and Interface Declarations
1. Class/interface documentation comment
```java
/**
*
*/
```
2. class or interface statement
```java
public class Clazz implements Serializable {
```
3. Class (`static`) variables
3.1 `public`
3.2 `protected`
3.3 package level (no access modifier)
3.4 private
```java
public static String SOMETHING_OPEN_TO_THE_WORLD = …;
protected static String SOMETHING_OPEN_TO_THE_PACKAGE = …;
static String SOMETHING_OPEN_TO_WTF = …;
private static String SOMETHING_OPEN_TO_ITSELF = …;
```
4. Instance variables
4.1 `public`
4.2 `protected`
4.3 package level (no access modifier)
4.4 private
```java
public String SOMETHING_OPEN_TO_THE_WORLD;
protected String SOMETHING_OPEN_TO_THE_PACKAGE;
SOMETHING_OPEN_TO_WTF;
private String SOMETHING_OPEN_TO_ITSELF;
```
5. Constructors
```java
public Clazz() {
}
```
6. Methods
> These methods should be grouped by functionality rather than by scope or accessibility. For example, a private class method can be in between two public instance methods. The goal is to make reading and understanding the code easier.
## Google Style Guide
```
public protected private abstract default static final transient volatile synchronized native strictfp
```
## 參考資料來源
1. [3 - File Organization](https://www.oracle.com/java/technologies/javase/codeconventions-fileorganization.html)