java方法参数

来源:互联网 发布:mac吃鸡 编辑:程序博客网 时间:2024/05/16 13:38
package cs.iot;
import java.util.Date;
import java.util.GregorianCalendar;
public class Employee {
public Employee(String name, double salary) {
super();
this.name = name;
this.salary = salary;
}
public Employee(String name, double salary, int id) {
super();
this.name = name;
this.salary = salary;
this.id = id;
}

private String name;
private double salary;
private int id;
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public int getId() {
return id;
}

public void raiseSalary(double byPercent){
double raise = salary * byPercent / 100;
salary += raise;
}

}






package cs.iot;
public class ParamTest {


public static void main(String[] args) {

//一个方法不能修改基本数据类型的参数
System.out.println("Testing tripleValue:");
double percent = 10;
System.out.println("Before: percent=" + percent);
tripleValue(percent);
System.out.println("After: percent=" + percent);

//一个方法可以改变对象参数的状态
System.out.println("\nTesting tripleSalary:");
Employee hary = new Employee("Harry", 5000);
System.out.println("Before: salary=" + hary.getSalary());
tripleSalary(hary);
System.out.println("After: salary=" + hary.getSalary());



//一个方法不能让对象参数引用一个新的对象
System.out.println("\nTesting swap: ");
Employee a = new Employee("Harry0", 7000);
Employee b = new Employee("Harry1", 8000);
System.out.println("Before: name =" + a.getName());
System.out.println("Before: name=" + b.getName());
swap(a,b);
System.out.println("After: name =" + a.getName());
System.out.println("After: name=" + b.getName());

}

public static void tripleValue(double x){ //does'n
x = 3 * x;
System.out.println("End of method: x=" + x);

}
public static void tripleSalary(Employee x){
x.raiseSalary(200);
System.out.println("End of method: salary=" + x);
}

public static void swap(Employee x, Employee y){
Employee temp = x;
x = y;
y = temp;
System.out.println(x.getName() +" "+x.getSalary());
System.out.println(y.getName() +" "+y.getSalary());
}
}


运行结果说明:

Testing tripleValue:
Before: percent=10.0
End of method: x=30.0
After: percent=10.0


Testing tripleSalary:
Before: salary=5000.0
End of method: salary=cs.iot.Employee@1b60280
After: salary=15000.0


Testing swap: 
Before: name =Harry0
Before: name=Harry1
Harry1 8000.0
Harry0 7000.0
After: name =Harry0
After: name=Harry1


0 0
原创粉丝点击