[Java] 類別 物件指定


//定義類別Exercise
class Exercise{
float floatExercise; //定義資料型態為浮點數之類別成員floatExercise

Exercise(float f) { //自訂建構函數,物件產生時執行
floatExercise = f; //將傳入的引數指定給類別成員floatExercise
}
}

public class Exercise_3_2 {

public static void main(String[] args) {

Exercise exercise1 = new Exercise(12.43f); //產生物件,引數傳入浮點數,利用建構函數指定給exercise1物件之類別成員floatExercise
Exercise exercise2 = new Exercise(10.642f); //產生物件,引數傳入浮點數,利用建構函數指定給exercise2物件之類別成員floatExercise
println("exercise1.floatExercise=" + exercise1.floatExercise);
println("exercise2.floatExercise=" + exercise2.floatExercise + '\n');

println("將exercise2物件指定給exercise1物件");
exercise1 = exercise2;
println("exercise1.floatExercise=" + exercise1.floatExercise);
println("exercise2.floatExercise=" + exercise2.floatExercise);
println("看似沒有問題\n");

println("將exercise2.floatExercise設為32.54");
exercise2.floatExercise=32.54f;
println("exercise1.floatExercise=" + exercise1.floatExercise);
println("exercise2.floatExercise=" + exercise2.floatExercise);
println("我們會發現exercise1.floatExercise也跟著改變,因為「exercise1 = exercise2」事實是將exercise2的位址傳給exercise1\n");

Exercise exercise3 = new Exercise(52.38f); //產生物件,引數傳入浮點數,利用建構函數指定給exercise3物件之類別成員floatExercise
Exercise exercise4 = new Exercise(76.31f); //產生物件,引數傳入浮點數,利用建構函數指定給exercise4物件之類別成員floatExercise
println("exercise3.floatExercise=" + exercise3.floatExercise);
println("exercise4.floatExercise=" + exercise4.floatExercise +'\n');

exercise3.floatExercise=exercise4.floatExercise;
println("我們要將函數成員exercise4.floatExercise直接指定給exercise3.floatExercise");
println("exercise3.floatExercise=" + exercise3.floatExercise);
println("exercise4.floatExercise=" + exercise4.floatExercise +'\n');

println("此時我們改變exercise4.floatExercise");
exercise4.floatExercise=8888.888f;
println("exercise3.floatExercise=" + exercise3.floatExercise);
println("exercise4.floatExercise=" + exercise4.floatExercise);
println("我們會發現exercise3.floatExercise沒有跟著改變,因為物件exercise3、exercise4沒有相同位址\n");
}

public static void print(String str) {
System.out.print(str);
}

public static void println(String str) {
System.out.println(str);
}

}

有疑問? 留個言吧!

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料