---
# System prepended metadata

title: JAVA教學---Defining Classes II
tags: [JAVA教學]

---

# JAVA教學---Defining Classes II

###### tags: `JAVA教學`
[TOC]


# 5.1 Static Methods and Static Variables

## Static method
:::warning
A static method is one that can be used without a calling object.
不用先宣告一個Object就可以使用。
:::
在**不同**class時的呼叫
```java
public static returnedType myMethod(parameters) 
{ . . . }
```
```java
returnedValue = MyClass.myMethod(arguments);
```
```java
public class StaticTest {
    public static void main(String[] args) {
        int sum = Tool.add(1,1);
        System.out.println(sum);
    }
}

public class Tool {
    public static int add(int a, int b){
        return a+b;
    }
}

```
:::warning
A static method **cannot** refer to an **nonstatic instance variable** of the class, and it cannot invoke a **nonstatic method** of the class.
:::

:::warning
A static method has no **this**, so it cannot use an instance variable or method that has an implicit or explicit this for a calling object.

However,a static method can invoke another **static method**,and **static instance variable**. 
:::

在**同個**class時的呼叫
```java=
public class Statictest {
	public static void main(String[] args) {
		int sum = add(1,1); 
		System.out.println(sum);
		
		Statictest st = new Statictest();
		sum = st.add2(2,2); // 不能用sum = add2(2,2);
		System.out.println(sum);
	}
	public static int add(int a, int b){
		return a+b;
	}
	public int add2(int a, int b){
		return a+b;
	}
}
```

## Static variables
:::warning
A static variable is a variable that belongs to the class as a whole, and not just to one object.
即所有透過這個Class宣告的Object都共用這個Static variable，有任一個Object改變了這個variable，其他Object也會受到改變.
:::
```java=
public class Statictest {
	public static int port = 80;
	
	public static void main(String[] args) {
		Statictest obj1 = new Statictest();
		Statictest obj2 = new Statictest();
		System.out.println(port);  //也可用Statictest.port
		System.out.println(obj1.port);  // 80
		System.out.println(obj2.port);  // 80
		port = 1234;
		System.out.println(obj1.port);  // 1234
		obj2.port = 5678;
		System.out.println(obj1.port);  // 5678
	}
}
```

## Math Class
**Math**提供多個數學計算method，且Math是在**java.lang package**，所以不需要import。
**Math**的所有**data**和**method**皆為**static**，直接用**Math.data**或者**Math.method**即可使用，不用再宣告一個物件。

Math的**predefined constants**有兩個，自然對數e和圓周率$\pi$
```java
double e = Math.E;
double pi = Math.PI;
```
* 指數計算
```java
public static double pow(double base, double exponent)
```
* 絕對值
```java
public static double abs(double argument)
public static float abs(float argument)
public static long abs(long argument)
public static int abs(int argument)
```
* 最小值
```java
public static double min(double n1, double n2)
public static float min(float n1, float n2)
public static long min(long n1, long n2)
public static int min(int n1, int n2)
```
* 最大值
```java
public static double max(double n1, double n2)
public static float max(float n1, float n2)
public static long max(long n1, long n2)
public static int max(int n1, int n2)
```
* 四捨五入
```java
public static long round(double argument)
public static int round(float argument)
```
* 取ceiling
```java
public static double ceil(double argument)
```
> Math.ceil(3.1) = 4.0
* 取floor
```java
public static double floor(double argument)
```
> Math.floor(3.9) = 3.0
* 開根號
```java
public static double sqrt(double argument)
```
* 隨機數
```java
public static double random()
```
> 0 $\leq$ 回傳值 $<$ 1


## Wrapper Classes
Every primitive type has a corresponding wrapper class. A wrapper class allows you to have a class object that corresponds to a value of a primitive type. Wrapper classes also contain a number of useful predefined constants and static methods.
:::warning
primitive type不是Object，所以不會有method。
primitive type對應的wrapper才是Object，才有相關method。
開頭小寫的是primitive type，開頭大寫的是Object。
:::
* boxing
```java
Integer integerObject = new Integer(42);
Double price = new Double(499.99);
Character grade = new Character('A');
```
:::danger
Wrapper Classes 沒有 no-argument constructor。
所以宣告時一定要帶入參數。否則會compile error。
:::

* auto-boxing
```java
Integer a3 = 5;
Double price = 499.99;
Character grade = 'A';
```
* unboxing
```java
int i = integerObject.intValue();
double d = price.doubleValue();
char c = grade.charValue();
```
* auto-unboxing
```java
int a = integerObject;
double d = price;
char c = grade;
```

:::danger
int count = new Integer(12); 
count 是 primitive type，不是 Object
:::


## Constants In Wrapper Classes
```java
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
System.out.println(Long.MAX_VALUE);
System.out.println(Long.MIN_VALUE);
System.out.println(Float.MAX_VALUE);
System.out.println(Float.MIN_VALUE);
System.out.println(Double.MAX_VALUE);
System.out.println(Double.MIN_VALUE);
```

## Static Methods in Wrapper Classes
* 數字String 轉成 數字
```java
int a = Integer.parseInt("123");
double b = Double.parseDouble("199.98");
```
* 數字 轉成 數字String
```java
String d = Integer.toString(123);
String c = Double.toString(199.98);
``` 
* 字元變大寫
```java
public static char toUpperCase(char argument)
```
* 字元變小寫
```java
public static char toLowerCase(char argument)
```
* 檢查大寫
```java
public static boolean isUpperCase(char argument)
```
* 檢查小寫
```java
public static boolean isLowerCase(char argument)
```
* 檢查空白，如 '\t' 和 '\n'
```java
public static boolean isWhitespace(char argument)
```
* 檢查字母
```java
public static boolean isLetter(char argument)
```
* 檢查數字
```java
public static boolean isDigit(char argument)
```
* 檢查字母或數字
```java
public static boolean isLetterOrDigit(char argument)
```

# 5.2 References and Class Parameters

## Variables and Memory
電腦有兩種 memory，分別為 **secondary memory** 和 **main memory** ，程式執行時會被放在 main memory。
Main memory 的 **address** 以 **byte** 為單位。Variable 至少占 1 個 byte。
**Variables** 有分為 **class type** 和 **primitive type**，但是兩者不太相同。
:::warning
***class type variable 和 primitive type variable 之間的差異***
A variable of a primitive type stores a value of that type. However, a variable of a class type **does not store an object of that class**. A variable of a class type stores the **reference (memory address)** of where the object is located in the **computer’s memory**. This causes some operations, such as = and ==, to behave quite differently for variables of a class type than they do for variables of a primitive type.
:::


## Reference
:::warning
***Reference Types***
A type whose variables contain references are called reference types. In Java, class types are **reference types**, but primitive types are **not reference types**.

Object 變數名稱存的值是 Object 的實際 **memory location**，不是實際的 **data**。
:::
```java
ToyClass variable1 = new ToyClass("Joe", 42);
ToyClass variable2;
variable2 = variable1; //Now both variables name the same object.
variable2.set("Josephine", 1);
System.out.println(variable1); //Invokes variable1's to String 
// Output 為 Josephine 1
// 因為 variable1 和 variable2 指向通一個 Object
```

## Class Parametrs
:::danger
傳入到某method裡，而在method裡使用的參數稱為 **Parameters**
而原本傳入的參數稱為 **Arguments**
:::
:::warning
***class type parameters 和 primitive type parameters 之間的差異***
primitive type parameters 是 **call-by-value** ，對 primitive type parameters 的改變**不會影響**到原本 arguments 本身。
class type parameters 是 **call-by-reference** ，對 class type parameters 的改變**會影響**到原本 arguments(object) 本身。
:::

```java=
public class ToyClass{
    private String name;
    private int number;
    
    public void makeEqual(ToyClass anObject){
        anObject.name = this.name;      // 會改變 anObject 原本所指向的 Object
        anObject.number = this.number;  // 會改變 anObject 原本所指向的 Object
    }
    
    public void tryToMakeEqual(int aNumber){
	aNumber = this.number;  // 不會改變原本傳入 aNumber 的值
    }
}
```

## The Constant null
The **constant** null is a special constant that may be assigned to a variable of any class type, used to indicate that the variable has **no “real value.”**
```java
YourClass yourObject = null;
```
**null** is not an object. It is like a reference (memory address) that does not refer to any object
:::warning
要比較一個 object 是否包含 null，要用 == 或者 != ，不要用equals()
:::
```java
if (yourObject == null)
     System.out.println("No real object here.");
```

:::danger
當1個 object 指向 null 時，它就**不能使用**任何 method，否則compiler會報錯出現 **"Null Pointer Exception"**。
:::

## The new Operator and Anonymous Objects
**new Operator** 是向 OS 要求一個 **memory location** 來存放 ToyClass Object，並且會回傳此 memory location，此記憶體位置由 variable1 接收。
```java
ToyClass variable1 = new ToyClass("Joe", 42);
```
當沒有變數接收**new Operator**所回傳的**memory location**時，則此 object 稱為 **anonymous Objects**，


# 5.3 Using and Misusing References




# 5.4 Packages and javadoc
:::warning
Although these are important topics, they are not used in the rest of this book. You can 
study this section at any time you wish; you need not cover this section before studying 
any other topic in this book
:::
```java
import java.util.Scanner; // 只引入java.util package 的 Scanner class
import java.util.*;         // 引入java.util package 的所有 class

```

## Pitfall: Subdirectories Are Not Automatically Imported
subdirectory不會自動import。須改為以下範例。
```java
import utilities.numericstuff.*;
import utilities.numericstuff.statistical.*;
```


