Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 809
Saksinkarn Petchkuljinda Avatar asked Dec 09 '25 05:12

Saksinkarn Petchkuljinda


2 Answers

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.

like image 101
Eran Avatar answered Dec 10 '25 18:12

Eran


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).

like image 33
Cristik Avatar answered Dec 10 '25 19:12

Cristik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!