-6

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 :)

WilliDK
  • 3
  • 3

3 Answers3

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.

Daisy Day
  • 652
  • 7
  • 19
0

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

int[] a = {1, 2, 3};

is legal in Java.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

There is no way to create an Object in Java without implicitly or explicitly calling the constructor and this involves creating a class which provides the blueprint for objects. (exception is by using deserialization)

Refer to this question for all the possible ways of creating Objects in java

Skillz
  • 308
  • 4
  • 10