• ConstructorTest


     1 public class ConstructorTest {
     2 
     3     /**
     4      * 重载构造器
     5      * 用this(...)调用另一个构造器
     6      * 无参数构造器
     7      * 对象初始化块
     8      * 静态初始化块
     9      * 实例域初始化
    10      */
    11     
    12     public static void main(String[] args) {
    13         // fill the staff array with three Employee objects
    14         Employee[] staff = new Employee[3];
    15         
    16         staff[0] = new Employee("Harry", 4000);
    17         staff[1] = new Employee(60000);
    18         staff[2] = new Employee();
    19         
    20         // print out information about all Employee objects
    21         for (Employee e : staff) {
    22             System.out.println("name = "+e.getName()+", id = " + e.getId()+", salary = "+e.getSalary());
    23             
    24         }
    25     }
    26     
    27 }
    28 
    29 class Employee
    30 {
    31     private static int nextId;
    32     
    33     private int id;
    34     private String name = "";     // instance field initialization
    35     private double salary;
    36     
    37     static
    38     {
    39         Random generator = new Random();
    40         // set nextId to a random number between 0 and 9999
    41         nextId = generator.nextInt(10000);
    42     }
    43     
    44     // object initialization block
    45     {
    46         id = nextId;
    47         nextId++;
    48     }
    49     
    50     // three overloaded constructors
    51     public Employee(String n, double s)
    52     {
    53         name = n;
    54         salary = s;
    55     }
    56     
    57     public Employee(double s)
    58     {
    59         // calls the Employee(String, double) constructor
    60         this("Employee #" + nextId, s);
    61     }
    62     
    63     // the default constructor
    64     public Employee()
    65     {
    66         // name initialized to "" --see above
    67         // salary not explicitly set --initialized to 0
    68         // id initialized in initialization block
    69     }
    70 
    71     public int getId() {
    72         return id;
    73     }
    74 
    75     public String getName() {
    76         return name;
    77     }
    78 
    79     public double getSalary() {
    80         return salary;
    81     }
    82     
    83     
    84 }

    name = Harry, id = 8654, salary = 4000.0
    name = Employee #8655, id = 8655, salary = 60000.0
    name = , id = 8656, salary = 0.0

  • 相关阅读:
    .net core2.0 中使用aspectcore实现aop
    [Superset] 设置Superset的登录设置
    [Python]Pandas对于非唯一的label index的数据选择问题
    Data Science Radar测试结果
    [R]R包版本更迭【持续更新】
    [面试] 删除多余的数组内容
    [Python]Python中的包(Package)
    [Linux] 使用Yum在CentOS上安装MySQL
    [pyMongo]insert_many的Bulkwrite实现机制
    [Git]2018-10 解决git cmd中文乱码问题
  • 原文地址:https://www.cnblogs.com/Night-Watch/p/12109870.html
Copyright © 2020-2023  润新知