第4章 对象构造 块执行顺序

来源:互联网 发布:网络平台推广是什么 编辑:程序博客网 时间:2024/05/27 00:48
package char04;import java.util.Random;public class ConstructorTest {/** * @param args */public static void main(String[] args) {Employee[] staff= new Employee[3];staff[0]=new Employee("harry",40000);staff[1]=new Employee(60000);staff[2]=new Employee();for(Employee e:staff){System.out.println("name= "+e.getName()+" id= "+e.getId()+" salary= "+e.getSalary());}}}class Employee{private static int nextId;private int id;private String name="";private double salary;//static initialization blockstatic{System.out.println("静态块---");Random g=new Random();nextId=g.nextInt(10000);}//object initialization block{System.out.println("object block");id=nextId;nextId++;}public int getId() {return id;}public String getName() {return name;}public double getSalary() {return salary;}public Employee(String name, double salary) {this.name = name;this.salary = salary;}public Employee(double salary) {//calls the Employee(Stirng,double) constructorthis("Employee #"+nextId,salary);}public Employee() {}}
执行结果:静态块---object blockobject blockobject blockname= harry id= 8067 salary= 40000.0name= Employee #8068 id= 8068 salary= 60000.0name=  id= 8069 salary= 0.0


原创粉丝点击