Java Custom Data Type

2019-10-03 06:41发布

I wanted to create a class with a custom data type that returns the class object. Consider a class Custom:

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

Now, consider a second 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
    }
}

So, the question how to get the value custom on instantiating an object instead of memory location. Like what I get is:

Custom@279f2327

3条回答
\"骚年 ilove
2楼-- · 2019-10-03 06:50

The Answer by ML72 is correct and should be accepted. The java.util.Date constructor captures the current moment in UTC.

java.time

The java.util.Date class is terrible, for many reasons. That class is now legacy, supplanted years ago but the java.time classes as of the adoption of JSR 310.

The java.time classes avoid constructors, instead using factory methods.

The replacement for java.util.Date is java.time.Instant. To capture the current moment in UTC, call the class method .now().

Instant instant = Instant.now() ;

If you want the current moment as seen through the wall-clock time used by the people of a particular region (a time zone), use ZoneId to get a ZonedDateTime object. Notice again the factory method rather than a constructor.

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

Adjust to UTC by extracting an Instant.

Instant instant = zdt.toInstant() ;
查看更多
神经病院院长
3楼-- · 2019-10-03 07:05

The java.util.Date class returns the current date. This can be seen as the constructor for the class is

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

For example, the following code would print out the current date:

DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
System.out.println(format.format(date));
查看更多
乱世女痞
4楼-- · 2019-10-03 07:05

Override the toString() method, as it is automatically invoked when you try to display an object:

Add a field. For example;

private String value;

In the constructor, add the following code:

value = custom;

this will assign a value passed to the constructor as a parameter, to the value field.

And finally override the toString() method as follows:

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

Now, when you display the value of the custom object, the overridden toString() method will be invoked and the argument will be displayed instead of the memory address. Whereas methods of the object will work as they are programmed to work. There is nothing to be changed with them.

查看更多
登录 后发表回答