I'm new to Java and working on a existing, big project. A couple times, I came across code like this: variable = (CustomClass) "string";.
Now, I really can't figure out why you would do that and how it is different from variable = new CustomClass("string");. The CustomClass has a constructor with one string argument.
In some situations, the above code just won't work which is why I came across it. But first, I want to understand what it does and Google doesn't seem to help. Or it is very possible I just don't know yet how to phrase the question accurately 😅
1 Answer
variable = (CustomClass) another_variable_reference;
Above line of code will tell JVM that another_variable_reference is-a class type of variable reference class, here CustomClass. So assign the reference to which another_variable_reference it is pointing to reference variable
variable = new CustomClass(another_variable_reference);
Above will create a new Object of CustomClass and assign the object reference to the variable
Hence, in the first case, we create a new reference which point's to an existing object while in second, we create a new Object and assign it's reference to variable
1 Comment
another_variable_reference was actually jListCustomers.getSelectedValue(), which my GUI editor somehow changed to type JList<String>. Changing the type to JList solved it.
CustomClass. This is suspicious to me, becauseStringis a final class, can't be extended, and so I doubt that this class could be used to cast a string.StringtoCustomClassand still have the code compile.