4

I can't understand how an object is created implicitly.

Example:

String s = "implicit instantiation";

Can I make my own class whose objects can be created implicitly?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
ankur_rajput
  • 145
  • 2
  • 11
  • 3
    In short: you can't. – OH GOD SPIDERS Apr 12 '17 at 14:14
  • 2
    `String` is a special object that has some syntactic sugar around it - string literals, concatenation operator, ability to be used in `switch` cases. Only Strings have that capability (arrays also have "literals"). – RealSkeptic Apr 12 '17 at 14:18

3 Answers3

3

No, String instantiation is handled implicitly by the compiler. Only the String and Array classes have this property.

String greeting = "Hello world!";
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };

Autoboxing allows you to implicitly instantiate objects of primitive wrapper types, but that's also a special case handled by the compiler. You can't create your own classes with this ability.

Boolean b = false;
Integer i = 0;
Double pi = 3.1416;
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
2

Unfortunately you just can not do that!

opposite to C or C++ you can not overload any operator in java language, so there is no possible way to do something like

Foo myFoo = 1

in the case of the string class:

String s = "implicit instantiation"

that is sugar sintax for the developers, behind the scenes is the compiler doing the "dirty" work and doing something like (remember there is a string pool):

String s = new String("implicit instantiation")

The same applies for some other Types like Arrays, or wrapper for numbers...

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

For every instance of an object you need a Constructor and a constructor its a a special method for construct and initialize methods. Example:

String s;  // Is not initialized and it's nos constructed.

So how do you construct a new object in java? Easy with the new operator you create a New Object!

s = new String("qwe"); // New object constructed

But here is something that a lot of newbies get confussed. Why i can do this:

String s= "asdfasd;" 

Because String is a special case in Java and you don't need to add a new operator like all the primitive variables that are classes. Example:

Integer i = 3; 
Double d = 3.3d;

and So on.

Gatusko
  • 2,503
  • 1
  • 17
  • 25