0

Let my class name is round. Why I have to write this syntax for dynamic memory alloc. like this........ round x = new round ();

I mean why to use class name. Why can't any other name....??

10th Jun 2017, 6:53 PM
Anshul Sharma
Anshul Sharma - avatar
4 Respostas
0
I'm not sure what you are asking. Why can't you use another class name? Or why do you have to use this syntax? ClassName varName = new ClassName(); That syntax is just how constructors work in Java. You can also use a factory: ClassName varName = MyClassFactory.create(); There are some other ways as well (using reflection, etc). Serialization for example. Most of the others rely on Constructors though.
11th Jun 2017, 2:26 AM
Jason Runkle
Jason Runkle - avatar
0
Yup...you interpreted it right.... but still its not clear to me that why constructor works this way. I mean there must be a reson developers kept the syntax this way...? I just want that reason..... please can you explain it to me...😁
11th Jun 2017, 2:54 AM
Anshul Sharma
Anshul Sharma - avatar
0
Well, sometimes you may have inheritance so you want the left side to be a different type. For example, HashMap implements Set and you really only care that it's a Set. So you may use this type of declaration: Set<String> names = new HashSet<>(); The new keyword is what tells the JVM to allocate memory for a new HashSet. Sometime down the road, you may want to use a different type of Set, for instance, a TreeSet. Then you just have to change one line to change the implementation: Set<String> names = new TreeSet<>();
11th Jun 2017, 7:14 AM
Jason Runkle
Jason Runkle - avatar
0
okay..... Now I got it.....thanks.....😄
11th Jun 2017, 8:19 AM
Anshul Sharma
Anshul Sharma - avatar