Is it possible to assign a string literal to an object in Java?
Like this:
String strLiteral = "String value";
MyClass obj = "String"; // Is this possible
Is it possible to assign a string literal to an object in Java?
Like this:
String strLiteral = "String value";
MyClass obj = "String"; // Is this possible
You're not trying to assign it to an object, you're trying to assign it to a variable of type MyClass
.
You can do that if String
is assignment-compatible to that class. For instance:
Comparable c = "Foo";
is fine, because String
is assignment-compatible with Comparable
, since String
implements Comparable
. The object is still a String
, it's just that we're accessing it through a variable of type Comparable
. (See What does it mean to “program to an interface”? for more on that concept.)
You can't do:
class Foo {
}
// Doesn't work
Foo f = "Foo";
because String
is not assignment-compatible with Foo
.
No you cannot, because MyClass
is not a superclass of String
.
One option is to make a static factory method fromString
on your class and use like so:
MyClass obj = MyClass.fromString("String");
In this method, you can define the conversion from a String
to a MyClass
.
String is Final Class you cannot extend string class and could not able to create subclass. So you cannot assign a string to different class name.