对象构造_练习

OverloadingTest

实例方法、静态方法、构造器都可以重载

public class OverloadingTest {
    private static int sum(int a, int b) {
        return a + b;
    }

    private static int sum(int a, int b, int c) {
        return a + b + c;
    }

    private static int sum() {
        return 0;
    }

    public static void main(String[] args) {
        int result1 = OverloadingTest.sum(1, 2);
        int result2 = OverloadingTest.sum(1, 2, 3);
        int result3 = OverloadingTest.sum();

        System.out.println(result1); // => 3
        System.out.println(result2); // => 6
        System.out.println(result3); // => 0
    }
}

ConstructorTest

Employee.java

import java.util.Random;

public class Employee {
    // 静态字段
    private static int nextId;
    private static Random generator = new Random();
    // 实例字段
    private int id;
    private String name = ""; // 在声明中赋值
    private double salary;

    static { // 静态初始化块,此部分请自学
        nextId = generator.nextInt(10000); // 将nextId设置为一个0到9999的随机数字
        System.out.println("静态初始化块 被执行了");
    }

    {
        this.id = nextId;
        nextId++;
        System.out.println("实例初始化块 被执行了");
    }

    // 3个重载的构造器
    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
        System.out.println("Employee(String, double) 被执行了");
    }

    public Employee(double salary) {
        this("Employee #" + nextId, salary);
        System.out.println("Employee(double) 被执行了");
    }

    public Employee() {
        System.out.println("Employee() 被执行了");
    }

    @Override
    public String toString() {
        // toString方法的用处请自学
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", salary=" + salary +
                '}';
    }
}

ConstructorTest.java

public class ConstructorTest {
    public static void main(String[] args) {
        Employee[] staff = new Employee[3];

        System.out.println("-----------1------------"); // 仅用于分隔,便于对照输出结果
        staff[0] = new Employee("张三", 4000);

        System.out.println("-----------2------------");
        staff[1] = new Employee(6000);

        System.out.println("-----------3------------");
        staff[2] = new Employee();

        System.out.println("-----------4------------");
        for (Employee e : staff) {
            System.out.println(e);
        }
    }
}

输出:

-----------1------------
静态初始化块 被执行了
实例初始化块 被执行了
Employee(String, double) 被执行了
-----------2------------
实例初始化块 被执行了
Employee(String, double) 被执行了
Employee(double) 被执行了
-----------3------------
实例初始化块 被执行了
Employee() 被执行了
-----------4------------
Employee{id=7190, name='张三', salary=4000.0}
Employee{id=7191, name='Employee #7191', salary=6000.0}
Employee{id=7192, name='', salary=0.0}

posted @ 2024-10-17 11:08  xkfx  阅读(109)  评论(0编辑  收藏  举报