+ 12

Is there a way to initialize an object without a constructor?

So in java when initializing a String you don't need to make use of a constructor, you just put in the literal but you can use the constructor if you please since String is a class. Now my question is is there any way to initialize a user-made class without the constructor?

15th Aug 2019, 2:14 PM
Ibrahim Adeosun
Ibrahim Adeosun - avatar
8 Réponses
+ 8
Well, Java String class is special because it is associated to how string literals are stored in the string pool. https://stackoverflow.com/questions/50302985/how-does-java-initialize-string-literal Based on some of the answers there, it seems like the assignment of a string literal to the String class also involves the calling of one of the constructors in the class, so technically it would be impossible to do classes without constructors, as constructors are always called when an object is initialized, even if it was designed to do nothing.
15th Aug 2019, 2:26 PM
Hatsy Rei
Hatsy Rei - avatar
+ 7
Maybe there are some unrecommended ways, but if you meant by that you don't want to define a constructor, then I can say that classes have a default constructor by default, which is just used to create the object self.
15th Aug 2019, 2:18 PM
Seb TheS
Seb TheS - avatar
+ 4
If I initialise member variables outside the constructor like this, is that considered as initialising an object without a constructor? ... No? https://code.sololearn.com/c7j319avp4Dd/?ref=app
17th Aug 2019, 12:39 AM
Sonic
Sonic - avatar
+ 2
Well, as a matter of fact, when you assign a literal to a string, you assign the memory address (heap) of the literal from the string pool to the String variable. It doesn't mean you do an intanciation. Keep in mind that String is immutable. You do the same with object that you assign to a class literal. String myString = ''Hello''; maClasse m1 = new maClasse(); maClasse m2 = m1;
15th Aug 2019, 9:08 PM
Geoffroy Malherbe
Geoffroy Malherbe - avatar
+ 1
No, I don't see any solution of it near me because object has to assign with constructor to initialized but good question to ask.
16th Aug 2019, 12:24 AM
Atif Saleem 🇵🇰
Atif Saleem 🇵🇰 - avatar
+ 1
String or text stored in string pool and doesn't need to make an object or constructor for strings but other classes and type are diffrent
16th Aug 2019, 2:37 PM
Artemis Ariamehr
Artemis Ariamehr - avatar
0
When you create a class, Java uses a default constructor if you do not define your own constructor. Even if you don't have a constructor in your class, you can still create objects. Example: class A{ } class B{ public static void main(String[] args){ A x = new A(); B y = new B(); //both are valid and the code will compile. Try running them to see the result. } }
16th Aug 2019, 3:07 AM
RexTRX
RexTRX - avatar
0
Primitive la third _ answer please
17th Aug 2019, 4:14 AM
Mohamed Zaini . IT