Java调用构造器的具体处理步骤:

1.所有数据域被初始化为默认值(0,false或null);

2.按照在类声明中出现的次序,依次执行所有域的初始化语句和初始化块;

3.如果构造器第一行调用了第二个构造器,则执行第二个构造器主体;

4.执行这个构造器的主体。

import java.util.*;
public class ConstructorTest {
    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()+",>e.getSalary());
        }
    }
}

class Employee
{
    public Employee(String n,double s)
    {
        name=n;
        salary=s;
    }
    public Employee(double s)
    {
        this("Employee #"+nextId,s);
    }
    public Employee()
    {
        
    }
    public String getName()
    {
        return name;
    }
    public double getSalary()
    {
        return salary;    
    }
    public int getId()
    {
        return id;
    }
    private static int nextId;
    private int id;
    String name="";
    private double salary;
    static
    {
        Random generator=new Random();
        nextId=generator.nextInt(10000);
    }
    {
        id=nextId;
        nextId++;
    }
}

运行结果:

name=Harry,id=4891,salary=40000.0

name=Employee #4892,id=4892,salary=60000.0

name=,id=4893,salary=0.0

相关文章:

  • 2021-10-15
  • 2021-12-26
  • 2021-09-19
  • 2021-09-05
  • 2022-12-23
  • 2021-08-13
  • 2021-09-01
猜你喜欢
  • 2022-12-23
  • 2021-12-03
  • 2021-09-30
  • 2021-07-01
  • 2021-09-29
  • 2021-11-24
  • 2021-05-25
相关资源
相似解决方案