Initializing objects in Java without declaring a class or using a class

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Initializing objects in Java without declaring a class or using a class



I have general question regarding objects in Java. I want to initialize an object in Java without declaring a class or using a class.



In python for example you can do like this:


myObject = {"x":5,"y":10,"z":12,"name":"something"}



Now myObject is an object. And I can say myObject.x which will be 5.



From what I know I would have to do like this in Java:


class object(){
int x;
int y;
int z;
String name;
myObject(int x, int y, int z, String name){
this.x = x;
this.y = y;
this.z = z;
this.name = name;
}
}

myObject = new object(10,5,12,"something")



I would like to do that, but like in my python example.
Hope anyone can help :)





"And I can say myObject.x which will be 5." No you can't. You're thinking of JavaScript. (Though I guess in JS you'd have to omit the quotation marks around the keys.)
– Aran-Fey
4 mins ago







@Aran-Fey OP presumably meant myObject.get('x').
– Elliott Frisch
2 mins ago




myObject.get('x')




2 Answers
2



Java is statically typed so you can't point a variable to an instantiated object without declaring the class.



You can create classes without a pointer but they will just be collected by the garbage collection machine unless you're passing them to something that uses the new object you're creating.



This is nothing in Java:



myObject = {"x":5,"y":10,"z":12,"name":"something"}



Java doesn't know what to do with it.



Java is not python, and you cannot instantiate a Java object with an anonymous Dict (the only type of object you can instantiate with a syntax like that is an array). That is, this


Dict


int a = {1, 2, 3};



is legal in Java.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

YKN rKrQsLlVHuIi6NLMYwYppPVgwp,JmTsh0i,G4huDZ44v4NAqL3MhV GKtnG
Um1dcv65Y4,qqnZ1laKJ vHMtmSH1J6u 05G,7y

Popular posts from this blog

Makefile test if variable is not empty

Visual Studio Code: How to configure includePath for better IntelliSense results

Will Oldham