Core Java (九) Java的方法參數

來源:互聯網
上載者:User

在各種程式設計語言中方法的參數有兩種,分別是:值調用,引用調用。

Java程式設計語言總是採用值調用,即方法得到了所有參數值的一個拷貝。

細分的話,方法參數一共兩種類型:

  1. 如果參數是基礎資料型別 (Elementary Data Type),那麼傳遞的是一個基礎資料型別 (Elementary Data Type)的值;
  2. 如果參數是對象,那麼傳遞的是一個對象引用的拷貝,注意不是C++中的對象引用。這個引用的拷貝和其他的拷貝一樣,同時引用了一個對象。

一個方法不可能修改一個基礎資料型別 (Elementary Data Type)的參數,但是可以修改一個對象的狀態。

一定要注意,Java中對對象採用的是引用的拷貝,並不是引用調用,反例如下:

測試程式:

package com.xujin;public class Test {public static void main(String[] args) {Employee[] staff = new Employee[2];staff[0] = new Employee("Bob", 1000);staff[1] = new Employee("Jim", 2000);//doesn't workswap(staff[0], staff[1]);System.out.println(staff[0].getName());//BobSystem.out.println(staff[1].getName());//Jimstaff[0].raiseSalary(0.5);//漲50%的工資System.out.println(staff[0].getSalary());//1500.0System.out.println(staff[0].getId());//1System.out.println(staff[1].getId());//2}public static void swap(Employee x, Employee y){Employee temp = x;x = y;y = temp;}}class Employee{public Employee(String name, double salary){this.name = name;this.salary = salary;id = nextId;nextId++;}public String getName(){return name;}public double getSalary(){return salary;}public int getId(){return id;}public void setName(String name){this.name = name;}public void setSalary(double salary){this.salary = salary;}public void raiseSalary(double percent){this.salary *= (1 + percent);}private String name;private double salary;private int id;private static int nextId = 1;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.