一、打印员工信息(方法参数)
public class ParamTest {
public static void main(String[] args) {
/*
* Test1:方法不能修改数值参数
*/
System.out.println("测试tripleValue:");
double percent = 10;
System.out.println("Before: percent="+percent);
tripleValue(percent);
System.out.println("After: percent="+percent);
/*
* Test2:方法可以改变对象参数的状态
*/
System.out.println("\n测试tripleSalary:");
Employee2 harry = new Employee2("Harry", 50000);
System.out.println("Before: salary="+harry.getSalary());
tripleSalary(harry);
System.out.println("After: salary="+harry.getSalary());
/*
* Test3:方法不能让对象参数引用一个新对象
*/
System.out.println("\n测试swap:");
Employee2 a = new Employee2("Alice", 70000);
Employee2 b = new Employee2("Bob", 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){ //不工作
x = 3 * x;
System.out.println("End of method: x="+x);
}
public static void tripleSalary(Employee2 x){ //工作
x.raiseSalary(200);
System.out.println("End of method: salary="+x.getSalary());
}
public static void swap(Employee2 x,Employee2 y){
Employee2 temp = x;
x = y;
y = temp;
System.out.println("End of method: x="+x.getName());
System.out.println("End of method: y="+y.getName());
}
}
class Employee2{ //简化员工类
private String name;
private double salary;
public Employee2(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;
}
}
二、打印员工信息(对象构造)
import java.util.*;
public class ConstructorTest {
public static void main(String[] args) {
//在staff数组中填充三个Employee对象
Employee3[] staff = new Employee3[3];
staff[0] = new Employee3("Harry", 40000);
staff[1] = new Employee3(60000);
staff[2] = new Employee3();
//打印关于所有Employee3对象的信息
for(Employee3 e : staff){
System.out.println("name="+e.getName()+",id="+e.getId()+",salary="+e.getSalary());
}
}
}
class Employee3{
private static int nextId;
private int id;
private String name = ""; //实例字段初始化
private double salary;
//静态初始化块
static{
Random generator = new Random();
//将nextId设置为0到9999之间的随机数
nextId = generator.nextInt(10000);
}
//对象初始化块
{
id = nextId;
nextId++;
}
//三个重载构造函数
public Employee3(String n,double s){
name = n;
salary = s;
}
public Employee3(double s){
//调用Employee3(String,double)构造函数
this("Employee3 #"+nextId,s); //构造器的第一个语句形如this(),将调用同一个类的另一个构造器
}
//默认构造函数
public Employee3(){
//将名称初始化为 ""--参见上面
//工资未显式设置——初始化为0
//id在初始化块中初始化
}
public String getName(){
return name;
}
public double getSalary(){
return salary;
}
public int getId(){
return id;
}
}