Is it possible to declare a variable without using "new" like "String" class

I want to achieve something like this. Declare and initialize a variable like those primitive data types.(Without having to use the new keyword)

MyClass myInstance = 123;

Similar to String. Only "String" type can do this and it's a class, too!

String myString = "A string!";

I want a way to declare some variable without using new like new MyClass(123)

Thank you!

Upvotes: 3

Views: 2265

Answers (2)

Cristik
Cristik

Reputation: 32782

123 is a number, myInstance is an object, they are not compatible, thus you cannot assign a number (or a string, or a boolean) to a variable of the MyClass type.

The only way this would be possible in the future is if Java would allow operator overloading (like C++ for example), for now you need to stick to myInstance = new MyClass(123).

Upvotes: 2

Eran
Eran

Reputation: 393771

You can't do it with custom classes.

The only classes that support such instantiation are String and the wrapper classes of the primitive types (Integer, Boolean, etc ...).

You could create instances of custom classes without the "new" if you use reflection, but then you'd be using newInstance() method of the Class class, which doesn't seem to be what you wish to achieve.

Upvotes: 8

Related Questions