Pregunta

In my programming class we are creating a class that resembles the Java String class. Right now, we create a new object like this :

MyString string = new MyString("Hello World");

Which is fine and all, but in Java you can create a new String object like this:

String string = "Hello World";

Is there someway to emulate that? Isn't this what people call immutable, where you can change the object after you create it, and add on to the object?

Edit: Apparently I need to go back to English class. The 'Im' in immutable means 'not'... Oops, I meant mutable.

¿Fue útil?

Solución

Being "immutable" is actually the opposite of what you describe; it means the object cannot be changed after creation or added to.

Regardless, this has nothing to do with immutability. There is no way to emulate that construction for your own classes. String literals are part of the bare bones specification of the language. Just like we have no operator overloading in Java (and thus have no way to make the compiler interpret + the way we'd like it to), we have no way to make the compiler understand a different set of literals. They just are what they are.

I'm sure there is some brilliant way to modify the JVM and create your own compiler to do what you want, but then you're not really using Java anymore.

You can read more about literals in the JLS 3.10, or the official Oracle tutorials (this one for Strings, this one for actual primitive types).

Otros consejos

In Java, string literals are instances of the String class. So in your second example, no conversion takes place. It has nothing to do with immutability (but you would run into problems if Strings were mutable).

EDIT: To see how the String class works internally, have a look at its source (OpenJDK).

Another example

Integer Int = 5;

OR

Integer Int = new Integer (5);

Both works fine.

Also the below works as well.

 Integer Int;
 int i = 5;
 Int = i ;

I think this is special behavior for few Types only. Possibly be the equal operator is overloaded.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top