2

I want to create my custom object using the assignment operator as the string does.

For example,

If I want to create an Object of employee class in a simple way like -

Class Employee{
   private String name;
   private int age;
   private String country; 
}

Employee employee = "Bagesh,27,India";

So is it possible to create an object the same way String class creates? or anyone can suggest the internal working of string assignment operator object creation.

I have already searched for it on many links but didn't get a complete answer.

Bagesh Sharma
  • 783
  • 2
  • 9
  • 23
  • 2
    The answer is no. It's not possible. – Eran Jan 29 '20 at 11:23
  • Does this answer your question? [Assignment Operator Overloading Java](https://stackoverflow.com/questions/15129284/assignment-operator-overloading-java) – Michael Hancock Jan 29 '20 at 11:24
  • 2
    Your best bet would be to create a constructor. Employee employee = new Employee("Bagesh",27,"India"); – SpaceCowboy Jan 29 '20 at 11:27
  • 2
    Only String literals can be created using assignment operator like this. Custom objects needs to be created via Constructors. String message = "Hello World"; – Zain Ul Abideen Jan 29 '20 at 11:29

2 Answers2

3

So is it possible to create an object the same way String class creates? [...] Employee employee = "Bagesh,27,India";

No, you can't do that. You'd need some form of operator overloading (either assignment overloading, or overloading of string quotes), and none of that is possible in Java.

You can do:

Employee employee = new Employee("Bagesh,27,India");

Though that would be odd, you might as well split your string up and do:

Employee employee = new Employee("Bagesh",27,"India");

If you wanted something a bit shorter, you could delegate to a separate method with a short name:

Employee employee = fromStr("Bagesh",27,"India");

...and implement fromStr() to call your constructor, though there's very little point in taking that approach in this example.

Other "flavours" of the above are all possible - factory classes, static factory methods, etc. - but none of them will give you the syntax you've defined in your question.

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
2

No, that is not possible.

The String class is special in Java. The compiler has special knowledge about it and knows how to generate byte code for e.g. the = operator (assign reference to a preallocated string in the String pool) and + operator (call .concat()).

tbsalling
  • 4,477
  • 4
  • 30
  • 51