# 定義類別

## 如何定義

每個 Java程式都會有一個或一個以上的類別。

> 類別是由「資料成員 field」與「函數 method」封裝而成。

```
class 類別名稱
{
   資料型態 field 名稱;
   ...
   傳回值的資料型態 函數名稱(引數1,引數2,...)
   {
     程式敘述;
     return 運算式;
   }
}
```

讓我們從第一個程式：Hello Java （[詳情請見](/java-01/hellojava.md)）帶入初次的解說吧\~

```
public class class01 {

	public static void main(String[] args) {

		 System.out.println("Hello Java!");

	}
}
```

看到 class class01 的地方，這邊就是一個類別！ 而其中的 main 就是他的(函數)成員唷。

### 實際範例

讓我們帶入實際的例子再做一次複習的說明：

一個矩形有「寬」與「高」，可以看成資料成員；而計算舉行面積或周長的函式，可以看成函數成員。

讓我們設計一個類別為矩形類別吧！

```
class CRectangle {  //定義矩形類別
	//資料成員
	int width;  //寬
	int height; //長

	//函數成員
	int area(){   //計算面積
		return width*height;
	}
	int perimeter(){  //計算周長
		return 2*(width+height);
	}
}
```

以上範例我們就成功定義了一個矩形的類別。

## 補充

在類別中，若要使用資料成員，可以直接使用資料成員中的變數名稱

如以上範例的矩形類別：直接使用資料成員中的寬與長。

```
//函數成員
	int area(){   //計算面積
		return width*height;
	}
	int perimeter(){  //計算周長
		return 2*(width+height);
	}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://java.4-x.tw/java-08/java-08-1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
