aspose file tools
The moose likes Java in General and the fly likes Building a class which initializes abject like String class? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Building a class which initializes abject like String class?" Watch "Building a class which initializes abject like String class?" New topic
Author

Building a class which initializes abject like String class?

malaya nayak
Greenhorn

Joined: Oct 31, 2009
Posts: 3
how can i create my own class that can be instantiated like we are creating string objects..

String s= "abc";

MyClass c= "xyz";// here my object should get initialized....
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 9956
    
    6

I'm not 100% sure, but I don't think you can. I believe that the String class gets special treatment by the compiler to allow that.

Now, I guess you COULD implement your own compiler that would give you this support for your class, but it's probably not worth it.


Never ascribe to malice that which can be adequately explained by stupidity.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32717
    
    4
And welcome to JavaRanch
Ulrika Tingle
Ranch Hand

Joined: Nov 24, 2009
Posts: 92
malaya nayak wrote:how can i create my own class that can be instantiated like we are creating string objects..

String s= "abc";

MyClass c= "xyz";// here my object should get initialized....


It's not possible in Java. The reason it works for String is because this particular class gets special language support to behave partly like a primitive.

You can come quite close though. Instead of using new you use a static creation class for your objects. And if you use a so called static import you don't need to prefix static methods of a class. The end-result would be something like,

MyClass c= create("xyz");

It's not perfect but it's as close as Java will take you at the moment.
malaya nayak
Greenhorn

Joined: Oct 31, 2009
Posts: 3
can you explain the procedure..

i am not able to find the create() method.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19216

You need to create it, but it can also be a constructor of the MyClass class itself:


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Building a class which initializes abject like String class?
 
Similar Threads
How can we create our own String class in java?
Difference between immutable and final class
assistance on casting operator
String Class
Loading user defined class