Java 自定义数据类型

Java Custom Data Type

我想创建一个 class 具有自定义数据类型的 returns class 对象。考虑 class 自定义:

public class Custom {
    // Some fields.
    public Custom(String custom) {
        // Some Text.
    }
    // Some Methods.
    public void customMethod() {
        // Some Code.
    }
}

现在,考虑第二个 class TestCustom:

public class TestCustom {
    public static void main(String[] args) {
        Custom custom = new Custom("Custom");
        System.out.println(custom); // This should print "Custom"
        custom.customMethod(); // This should perform the action
    }
}

所以,问题是如何在实例化对象而不是内存位置时获取自定义值。就像我得到的是:

Custom@279f2327

java.util.Dateclassreturns当前日期。这可以看作是 class 的构造函数是

public Date() {
    this(System.currentTimeMillis());
}

例如,以下代码将打印出当前日期:

DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
System.out.println(format.format(date));

是正确的,应该接受。 java.util.Date 构造函数以 UTC 格式捕获当前时刻。

java.time

java.util.Date class 很糟糕,原因有很多。 class 现在是遗留物,几年前就被取代了,但是 java.time class 是 JSR 310 的采用。

java.timeclasses 避免使用构造函数,而是使用工厂方法。

java.util.Date 的替换为 java.time.Instant。要以 UTC 格式捕获当前时刻,请调用 class 方法 .now().

Instant instant = Instant.now() ;

如果您希望通过特定地区(时区)的人们使用的挂钟时间看到当前时刻,请使用 ZoneId 获取 ZonedDateTime 对象。再次注意工厂方法而不是构造函数。

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

通过提取 Instant 调整为 UTC。

Instant instant = zdt.toInstant() ;

覆盖 toString() 方法,因为它会在您尝试显示对象时自动调用:

添加一个字段。例如;

private String value;

在构造函数中,添加以下代码:

value = custom;

这会将作为参数传递给构造函数的值分配给 value 字段。

最后重写 toString() 方法如下:

@Override
public String toString() {
    return value;
}

现在,当您显示自定义对象的值时,将调用覆盖的 toString() 方法并显示参数而不是内存地址。而对象的方法将按照编程的方式工作。他们没有什么可以改变的。