一直以来 我一直都在想:Java到底是传值还是传引用
想不清楚,与舍友讨论结果是简单类型传值,object类型传引用,咋看上去好像没错,其实我觉得所有的类型都是传值,而没有传引用
测试代码如下:
/* * To change this template, choose Tools | Templates * and open the template in the editor. */
package javavaule;
/** * * @author duxingxia */ public class Main {
/** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here
/* * test 1:Methos can't modify numeric paramenters */ System.out.println("Testing tripleVaule:"); double percent = 10; System.out.println("Before: percent="+percent); tripleValue(percent); System.out.println("After: percent="+percent);
/* * test 2:Methods can change the state of object paramenters */ System.out.println("\nTesting tripleSalary:"); Employee harry = new Employee("Harry",50000); System.out.println("Before: salary="+harry.getSalary()); tripleSalary(harry); System.out.println("After: salary="+harry.getSalary());
/* * test 3:Methods can't attach new objects to object paramenters */ System.out.println("\nTesting swap:"); Employee a = new Employee("Alice",70000); Employee b = new Employee("Bod",60000); System.out.println("Before: a ="+a.getName()); System.out.println("Before: b ="+b.getName()); swap(a,b); System.out.println("After: a ="+a.getName()); System.out.println("After: b ="+b.getName());
} public static void tripleValue(double x)//doesn't work
{ x = 3 * x; System.out.println("End of Method: x=" + x); } public static void tripleSalary(Employee x)//works
{ x.raiseSalary(200); System.out.println("End of method: salary="+x.getSalary()); } public static void swap(Employee a,Employee b) { Employee temp = a ; a = b; b = temp; System.out.println("End of method: a="+a.getName()); System.out.println("End of method: b="+b.getName()); }
}
class Employee { 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; return; } private String name; private double salary; }
|
输出地截图如下:
阅读(819) | 评论(0) | 转发(0) |