# 物件與類別 ###### tags: `java` --- ## 認識物件與類別 ### 類別 1. 用狗做例子,它的特性有名字、年齡、顏色等,它的行為有睡覺、跑、叫、搖尾巴。 2. 用手機做例子,它的特性有顏色、型號、尺寸、版本,它的行為有照相、計時、錄音、鬧鐘等(功能)。 因此狗、手機就是一個類別,物件的特性就是所謂的屬性(attributes)或者稱為欄位(fields),物件的行為就是所謂的方法(method)。 | **** | 手機類別 | 狗類別 | | ---- | -------- | ------ | | 屬性 | 顏色 | 名字 | | 屬性 | 型號 | 年齡 | | 屬性 | 尺寸 | 顏色 | | 方法 | 照相 | 睡覺 | | 方法 | 鬧鐘 | 跑 | | 方法 | 錄音 | 搖尾巴 | --- ### 物件 ``` import java.util.*; class Main { public static void main(String[] args) { Dog mydog=new Dog(); mydog.name="joyce"; mydog.color="purple"; mydog.age=8; mydog.barking(); Dog TomDog =new Dog(); } } class Dog{ String name ; String color; int age; void barking(){ System.out.println("my dog is barking."); } } ``` Dog 就是一个类别,而mydog、TomDog则是建立的“物件” 虽然使用相同的属性方法,但是彼此是独立的。 --- ### 宣告與建立類別物件 類別定義完成後,我們需要**宣告**與**建立**這個類別物件 ``` Dog myDog; myDog = new Dog(); ``` > 在類別中。我們稱此為**建構方法**或**建構元/建構子** --- ## 類別的基本實例 ### 建立類別的屬性 類別屬性(Attributes)記載著類別的特色,使用時須為屬性建立**變數(Variables)**,然後才可進行存取。 ``` class Dog{ String name; String color; int age; } ``` ### 存取類別的成員變數
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up