[toc]
https://docs.oracle.com/javase/tutorial/java/javaOO/classdecl.html
## Class (類別)
**一個.java file只能有一個public修飾的 class**
Class(類別) 可以說是物件藍圖
---
### 宣告Class
這是一個最簡單的class宣告。
Class Name 請用大駝峰命名。
```java
class MyClass { // class body, not-a-block
/*
這裡可以宣告
- 成員變數(member variable) (field)
- 建構子(constructor)
- 方法(method)
這些都是class的成員。
*/
}
```
---
### 宣告成員變數(Field)
由三個部分組成.
- {0,} 個修飾符, 如access modifiers...
- Data Type
- Name
除了被`static final`的變數, 請用小駝峰命名法.
Example:
```java
class Point {
public int x;
public int y;
}
```
---
基於封裝精神, 把Field設為private是很常見的行為,
只寫有需要調用的方法, 像是getter, setter會使程式碼更好維護。
(有些看不懂沒關係)
```java=
//---------- in Point.java ----------
class Point {
private int x;
private int y;
//getter & setter
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int newVal) {
x = newVal;
}
public void setY(int newVal) {
y = newVal;
}
}
//---------- in Main.java ----------
public class Main {
public static void main(String[] args) {
Point p = new Point();
p.setX(100);
p.setY(200);
System.out.println(p.getX() + " " + p.getY()); // 100 200
}
}
```