package com.wana; import java.time.LocalDate; /** * @author JackZhao * @create 2020-03-24 下午 12:47 */ public class EmployeeTest { public static void main(String[] args) { Employee[] staff = new Employee[3]; //构建employee数组 staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15); staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1); staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15); //为数组填入对象 for (Employee e : staff) e.raiseSalary(5); //像极了py的for语句实在好用,处理Employee数组staff。 for (Employee e : staff) System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay=" + e.getHireDay()); } } class Employee { private String name; private double salary; private LocalDate hireDay; public Employee(String n, double s, int year, int month, int day)//(构造器)处理Employee数组填入的对象信息 { name = n;//此处均为实例字段变量而不是局部变量,例如:String name 则是个局部变量 salary = s; hireDay = LocalDate.of(year, month, day); } public String getName() { return name; }//返回名字的方法 public double getSalary() { return salary; }//返回薪水的方法 public LocalDate getHireDay() { return hireDay; }//返回入职时间的方法 public void raiseSalary(double byPercent)//增长薪水的方法 { double raise = salary * byPercent / 100; salary += raise; } } /*原来可以这样用:1.根据一个类构建一个数组; 2.再用类中的方法处理填入数组对象的信息。*/
2020-03-26
参数顺序
staff[0] = new Employee("Tom", 40000); //参数要一一对应,构造器Employee中是先String再double
//附上Employee构造器:
public Employee(String n, double s)
{
name = n;
salary = s;
id = 0;
}
for each循环
for (Employee e : staff)//Employee变量e依次(从staff[0],staff[1],staff[2])遍历数组staff。 { e.setId(); //等价于staff[0].setId(); // 等价于staff[1].setId(); // 等价于staff[2].setId();
}
注意:实例变量和局部变量的使用;
构造器与类同名,这样在构造对象时,构造器才会启动,对实例字段进行初始化(信息处理)
隐式参数与显式参数
public void raiseSalary(double byPercent) { double raise = salary * byPercent / 100; salary += raise; } /*关键字this将实例字段同局部变量区分开来/ public void raiseSalary(double byPercent) { double raise = this.salary * byPercent / 100; this.salary += raise;//this指代隐式参数(Employee对象) }
2020-04-22补充:
package com.company; import java.lang.reflect.Array; import java.util.Arrays; /*创建数组时,所有元素初始化为0,如:布尔数组为false 对象数组为null*/ public class array { public static void main(String[] args) { String[] s;//声明数组 var a= new int[100];//创建数组 int[] b={1,5,8,9,};//创建并初始化数组 var d=new int[]{16,22};//创建·并初始化一个匿名数组 /*二维数组(即数组数组)*/ int[][] f;//声明 f = new int[1][2];//初始化 int[][] g={{1,25},{5,58}};//创建并初始化数组 //二维数组需要一个嵌套for each语句来遍历;可使用Arrays.deepToString()打印二维数组。 System.out.println(Arrays.deepToString(g)); /*交换二维行*/ int[] i =g[1]; g[1]=g[0]; g[0]=i; System.out.println(Arrays.deepToString(g)); } }