Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
5.00/5 (3 votes)
See more:
Does such a thing exist in Java? For example, I can always do something like:

AJSDate startDate = new AJSDate("20090811");
but I would rather have it as:

AJSDate startDate = "20090811";

Posted
Updated 14-Jul-18 13:25pm
v2

No, you cannot do this in Java. It was a deliberate choice by Gosling et al. as one of their original design aims for the language was simplicity and transparency: you should always know what code does simply by looking at it, with no "hidden" effects. ("Simplicity" and Java, oh how the world has changed.)
What you can do is set up a static factory method, something like:

Java
AJSDate startDate = AJSDate.valueOf("200090811");


That's probably a better solution for dates if you're concerned about time zones because it allows you to overload the factory method to specify a time zone as well, which you can't easily do with operator overloading.
 
Share this answer
 
v2
Java does not really work like Javascript, though recent changes brought by Java 10 and local variable type inference may help a bit with this. Before Java 10, objects were specifically defined (ah well, even after Java 10) and interpreted, so when you have

AJSDate startDate = new AJSDate("20090811");


... it tells the JVM you want an object of type AJSDate to be generated with that specific String object, injected into the provided constructor (I assume by you).

With Java 10 when you have local variables, you can however have something along the lines of this (local variable type inference):

public void someMethod() {
var startDate = new AJSDate("20090811");
}

The Java 10 method using var gets really close to how Javascript behaves sometimes, but not entirely. Security of an app, relies heavily on type safety. Having something like this:

AJSDate startDate = "20090811";


Would pretty much through an error, because you would want to equate two different object types.
 
Share this answer
 
Comments
Dave Kreskowiak 14-Jul-18 19:43pm    
Really? Asked and accepted answered NINE YEARS ago.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900