靜態與非靜態呼叫

static / instance
static表示靜態的
(我覺得這個翻譯有點爛,但好像也找不到更好的說法了)
簡單來說就是可以直接 類別名稱.方法 來呼叫
若沒寫 static 表 “ 實例函數 instance ” (又稱非靜態方法 , 實例方法)而實例函數 需要先建立物件才能呼叫
說例
public class MyMath { // 定義一個公共類別
static int mul(int x, int y) {return x*y; }
int div (int x, int y) { return x/y; }
}
呼叫 mul
int product = MyMath.mul(12, 12);
呼叫 div
MyMath mMath = new MyMath();
int quo = mMath.div(12, 12);
傳值呼叫 與 參考呼叫
傳值呼叫 就是直接傳 int double 等基本數據型態 ,若是傳其他的如物件或list等 則參考呼叫
實 / 虛參數
參數 又稱引數
在java 中 引數分為 實引數與虛引數
寫在自訂義方法那的 叫 虛引數
public class Main {
public static void display(int number) { // 虛引數
System.out.println("接收到的數值: " + number);
}
public static void main(String[] args) {
int x = 10;
display(x); // 實引數為 x
}
}
public static void callAdd( ) {
int anum = 100;
for (int cnt = 0; cnt < 100; cnt++) { add(anum); }
System.out.println(anum); // 輸出
}
public static void add(int anum) { anum++;//改變的是虛引數的anum }
//輸出100
結論
在「傳值呼叫」中,「實引數」與「虛引數」二者占不同 記憶體位置
在「參考呼叫」中,「實引數」與「虛引數」二者占相同 記憶體位置
private 與 public

private | 只能在該類別內使用,外部無法存取。 |
|---|---|
public | 可以從 任何地方 存取,包括不同的類別。 |
外部類別透過get, set方法來存取資料
範例
Person.java
public class Person {
private String name; // 私有變數,僅能在 Person 類別內部存取
// 提供公開的方式讓外部可以安全地存取 private 成員
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
App.java
public class App {
public static void main(String[] args) {
Person person = new Person(); // 創建 Person 類別的物件
// person.name = "John"; // 錯誤!無法直接存取 private 成員
person.setName("John"); // 正確!透過 public 方法修改值
System.out.println(person.getName()); // 正確!透過 public 方法讀取值
}
}
在類別中定義建構式不用void,直接 public Class() { A=x ; B=y }
建構式 Constructor

類別中的一種特殊方法,用於初始化物件。建構式的名稱必須與類別名稱相同,且沒有回傳型別
所以在物件基礎認識那篇我們有說到
透過建構式創建物件的語法如下
類別名稱 物件名稱 = new 建構式名稱(引數)
之後我們要賦予我們類別內的屬性方法都要用以下寫法
myDog.name = "Harry"; // 設定屬性初值
可是這樣會降低程式的可讀性
所以我們可以直接在 class 中 “ 定義建構式 ”
語法如下
class Rectangle {
double width;
double len;
// 自定義建構式
public Rectangle(double width, double len) {
this.width = width;
this.len = len;
}
}
public class Main {
public static void main(String[] args) {
// 使用建構式初始化屬性
Rectangle r = new Rectangle(5.0, 10.0);// 直接寫入初值
System.out.println("寬度: " + r.width + ", 長度: " + r.len);
}
}
如果沒有先定義建構式則要寫成這樣
class Rectangle {
double width;
double len;
}
public class Main {
public static void main(String[] args) {
Rectangle r = new Rectangle();
r.width = 5.0; // 必須手動設定屬性
r.len = 10.0;
System.out.println("寬度: " + r.width + ", 長度: " + r.len);
}
}