Can I create a class that instantiates with just the =
operator, like the String
class does? Or is that a feature specific to String
class in Java?
No, you can't create a class that's instantiated just with =
operator because you can't overload an operator in Java like you can in C++ or C# (see Operator overloading in Java).
String
s are instantiated when you use "something"
only if they do not already exist in memory, so you get a reference to the same exact String
object each time you write "something"
.
For example, if you do:
String a = "something";
String b = "something";
Then
a == b; // will be true.
You can take a look at these questions to learn more about how String
objects work:
Strings are objects in Java, so why don't we use 'new' to create them?
What is the difference between "text" and new String("text")?
What is Java String interning?
Because Java does not support user-defined Operator Overloading a new instance can not be created with =
Operator.
Check out Why doesn't Java offer operator overloading? for more information
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With