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
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
isjava.time.Instant
. To capture the current moment in UTC, call the class method.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 aZonedDateTime
object. Notice again the factory method rather than a constructor.Adjust to UTC by extracting an
Instant
.The java.util.Date class returns the current date. This can be seen as the constructor for the class is
For example, the following code would print out the current date:
Override the
toString()
method, as it is automatically invoked when you try to display an object:Add a field. For example;
In the constructor, add the following code:
this will assign a value passed to the constructor as a parameter, to the
value
field.And finally override the toString() method as follows:
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.