方法参数共有两种类型
1.基本数据类型(数字、布尔值)
2.对象引用(值传递)
思考
1.方法是否能够修改传递给它的参数变量内容?
2.方法是否能够改变一个对象参数的状态?
3.方法是否让对象参数引用一个新的对象?
进行代码验证:
class Employee
{
private static int nextId = 1;
private String name;
private double salary;
private int id;
public Employee(String n,double s)
{
name = n;
salary = s;
id =0;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public int getId()
{
return id;
}
public void setId()
{
id = nextId;
nextId++;
}
public static int getNextId()
{
return nextId;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
public static void main(String[] args)
{
Employee e = new Employee("Harry",50000);
System.out.println(e.getName()+" "+e.getSalary());
}
}
public class ParamTest
{
public static void main(String[] args)
{
System.out.println("测试方法是否能够修改传递给它的参数变量内容");
double percent = 10;
System.out.println("Before: percent="+percent);
tripleValue(percent);
System.out.println("After: percent="+percent);
System.out.println();
System.out.println("测试方法是否能够改变一个对象参数的状态");
Employee harry = new Employee("Harry",50000);
System.out.println("Before: salary="+harry.getSalary());
tripleSalary(harry);
System.out.println("After: salary="+harry.getSalary());
System.out.println();
System.out.println("测试方法是否让对象参数引用一个新的对象");
Employee a = new Employee("Alice",7000);
Employee b = new Employee("Bob",6000);
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)
{
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.getSalary());
}
public static void swap(Employee x,Employee y)
{
Employee temp = x;
x = y;
y = temp;
System.out.println("End of method:x="+x.getName());
System.out.println("End of method:y="+y.getName());
}
}
验证结果
总结:
1.方法不能够修改传递给它的参数变量内容;
2.方法能够改变一个对象参数的状态;
3.方法不能让对象参数引用一个新的对象。