J一般语言例如C++,都支持按值传递和引用传递。而在Java中支持按值传递,也就是所说的对象引用,下面是对其传递参数的示例。
package com.company; public class Main { public static void main(String[] args) { // write your code here //Test 1 System.out.println("Testing triplevalue:"); double percent=10; System.out.println("Before:percent="+percent); triplevalue(percent); System.out.println("After:percent="+percent); //Test 2 System.out.println("\nTesting triplesalary:"); Employee harry=new Employee("Harry",50000); System.out.println("Before:salary:"+harry.getSalary()); triplevalue(harry); System.out.println("After:salary"+harry.getSalary()); //Test 3 System.out.println("\nTesting swap:"); Employee a=new Employee("Alice",7000); Employee b=new Employee("Bob",8000); System.out.println("Before:a="+a.getSalary()); System.out.println("Before:b="+b.getSalary()); swap(a,b); System.out.println("After:a="+a.getName()); System.out.println("After:b="+b.getName()); } public static void triplevalue(double x){ x=3*x; System.out.println("End of method:x="+x); } public static void triplevalue(Employee x){ x.raiseSalary(200); System.out.println("End of the method:Salary="+x.getSalary()); } public static void swap(Employee x,Employee y){ Employee temp; temp=x; x=y; y=temp; System.out.println("End of the method:x="+x.getName()); System.out.println("End of the method:y="+y.getName()); } } class Employee{ private String name; private double salary; public Employee(String n,double s){ name=n; salary=s; } public String getName(){ return name; } public double getSalary(){ return salary; } public void raiseSalary(double byPercent){ double raise=salary*byPercent/100; salary+=raise; } }
运行结果:
Testing triplevalue:
Before:percent=10.0
End of method:x=30.0
After:percent=10.0
Testing triplesalary:
Before:salary:50000.0
End of the method:Salary=150000.0
After:salary150000.0
Testing swap:
Before:a=7000.0
Before:b=8000.0
End of the method:x=Bob
End of the method:y=Alice
After:a=Alice
After:b=Bob
由此知道Java中的对象引用传递参数。