# JAVA教學---Defining Classes I ###### tags: `JAVA教學` ## 目錄 [TOC] ## define Java的class是什麼? >Every program is a class >All helping software consists of classes >All programmer-defined types are classes :::warning :bulb: **原則**: define your own classes and their attribute and methods, and to create your own objects from classes ::: ## 名詞解釋 ```java= public class Car { public int xPosition = 0; public void moveForward(){ xPosition++; } } ``` int 等敘述稱為這個 class(Car) 的 attribute、field、instance、variable。 function 稱為這個 class(Car) 的 method、function、behabior、operator。 但是兩者皆是這個 class(Car) 的 member。 >A primitive type value is a **single piece of data** >A class type value or object can have **multiple pieces of data**, as well as actions called methods >For a given object, each piece of data can hold a **different** value ## 使用方式 宣告 ``` ClassName classVar; ``` 給值,可在括號內給予data做initialization ``` classVar = new ClassName(); ``` 宣告同時給值 ``` ClassName classVar = new ClassName(); ``` ## Local Variables A variable declared within a method definition is called a local variable >All variables declared in a method are local variables. >All method parameters are local variables. > ![](https://i.imgur.com/kj0egx4.png) If two methods each have a local variable of the same name, they are still two entirely different variables ## Variable Argument (Varargs) 接收多個相同型態變數的方法,若有不同型態則不能用 ```java= public static void main(String args[]) { display("Tom");// zero argument display("my", "name", "is", "Tom");// four arguments } static void display(String... values) { System.out.println(values[0]); } ``` ## Call-by-value (Primitive Type) The value of each argument (not the variable name) is plugged into the corresponding method parameter >known as the call-by-value mechanism ## this. 用法 如果想要透過Class裡的**method**修改Class裡的**instance**時,==而且method的parameter和instance名稱相同時==,需要在前面加上**This.**,才能存取該**instance**,否則會變成local variable。 :::warning 即便 method 的 parameter 和 Class 裡的 instance 名稱不同,也最好加上**this.**,用以表明是用來修改 Class 裡的 instance。 ::: ```java= public class Car { public int xPosition = 0; public void moveToGiven(int xPosition){ this.xPosition = xPosition; //用來修改Class裡的xPosition } } ``` ## Encapsulation 封裝 Encapsulation means that the data and methods of a class are combined into a single unit (i.e., a class object),which hides the implementation details > Knowing the details is unnecessary because interaction with the object occurs via a well-defined and simple interface >In Java, hiding details is done by marking them **private** :::danger 把 object 的 attribute 設為 private,包起來成為一個set,不讓外界輕易來改,而是透過寫 get 和 set 的 public method 來決定是否要讓外界class來 read 或 write 這些 object 的 attribute ,這一系列操作稱為 Encapsulation,是OOP裡最基本且重要的原則,也可減少 bug 發生的機率。 ::: ## public and private Modifiers * public : there are **no restrictions** on where an instance variable or method can be used. * private : an instance variable or method **can only be accessed** by name **inside** of the class :::warning 1. It is considered good programming practice to make all instance variables **private**. 2. Most methods are **public**, and thus provide controlled access to the object. 3. Usually, methods are **private** only if used as helping methods for other methods in the class. ::: demo如下 ```java= public class Car { private int position = 0; public Car(int position){ this.position = position; } public void moveForward(){ position++; } public void moveToGiven(int position){ this.position = position; } public int getPosition(){ return position; } } ``` ```java= public class demo { public static void main(String[] args) { Car bmw = new Car(2); System.out.println("Car position = " + bmw.getPosition()); bmw.moveForward(); System.out.println("Car position = " + bmw.getPosition()); bmw.moveForward(); System.out.println("Car position = " + bmw.getPosition()); bmw.moveToGiven(6); System.out.println("Car position = " + bmw.getPosition()); } } ``` ## Overloading 定義 : 發生於class中的兩個method有**相同name**時 解決方法 : 讓兩個method有不同的parameter list,及參數不同 ```java= public class Duck { public void quack(){ System.out.println("Quack!!"); } public void quack(String sound){ System.out.println(sound); } } ``` :::warning Overloading可用於user輸入多種parameters的狀況 ::: ## Constructors 建構子 定義 : a special kind of **method** that is designed to **initialize** the **instance variables** for an object. * Constructors 的名稱需和 class **相同**。 * A constructor has no type returned, not even void. * Constructors are typically overloade. 定義 Constructors ```java public ClassName(anyParameters){code} ``` 使用 Constructors ```java ClassName objectName = new ClassName(anyParameters); ``` :::warning 若不想用 Constructor 做任何初始化,則不用重新定義Constructor,在 new Object 時不用帶入任何參數,Java 會自動 new 一段 memory location 並給予 default 值。 ::: ## StringTokenizer Class 用途 : 重新定義字串的separator ```java= import java.util.StringTokenizer; public class StringTokenizerTest { public static void main(String[] args) { String input = "Hello,World,Java"; StringTokenizer st = new StringTokenizer(input, ","); while(st.hasMoreTokens()) { String token = st.nextToken(); System.out.println(token); System.out.println("Reamin Tokens = " + st.countTokens()); } } } ```