在 'Person' 类的构造方法中调用本类已声明的构造方法来创建 'MyDate' 实例的示例代码如下:

public class Person {
    private String name;
    private MyDate birthdate;

    // 无参数构造方法
    public Person() {
        this.name = "";
        this.birthdate = null;
    }

    // 调用本类声明的构造方法,参数创建 MyDate 实例的构造方法
    public Person(String name, int year, int month, int day) {
        this.name = name;
        this.birthdate = new MyDate(year, month, day);
    }

    // 其他代码...
}

在上述示例中,我们添加了一个具有参数的构造方法,该构造方法根据给定的姓名和年、月、日参数创建 'MyDate' 实例。我们在构造方法中使用 'new MyDate(year, month, day)' 来创建 'MyDate' 实例,并将其赋值给 'birthdate' 成员变量。这样,当调用这个构造方法创建 'Person' 对象时,就可以同时创建并设置 'MyDate' 实例。

Java 中使用构造方法创建 MyDate 实例

原文地址: https://www.cveoy.top/t/topic/lcT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录