-2

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

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

现在,考虑第二类 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
4

3 回答 3

2

java.util.Date 类返回当前日期。这可以看作是类的构造函数是

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

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

DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
System.out.println(format.format(date));
于 2019-08-25T22:32:46.270 回答
2

ML72的回答是正确的,应该被接受。构造函数捕获 UTC 中的java.util.Date当前时刻。

java.time

java.util.Date门课很糟糕,原因有很多。该类现在是遗留的,多年前被取代,但java.time类在 JSR 310 采用时已被取代。

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

的替代品java.util.Datejava.time.Instant。要以 UTC 捕获当前时刻,请调用类方法.now()

Instant instant = Instant.now() ;

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

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

通过提取Instant.

Instant instant = zdt.toInstant() ;
于 2019-08-26T00:10:31.107 回答
1

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

添加一个字段。例如;

private String value;

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

value = custom;

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

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

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

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

于 2019-09-02T05:12:42.043 回答