Skip to content
Advertisement

Is it possible to have values for class object in java, if yes how can we acquire it?

Let’s say, I am initializing a class obj as follows:

<class> obj = <some value>;

Is it possible to initialize as such I mean we initialize String and primitive values like that, But I mean for any class. And how can we get them so they can be used in some method of the same class?

Advertisement

Answer

Yes if it is for built in types like string, int, float etc. These built in types are pass by value. Which means if you say int a = 5, 5 is copied over to memory location.

If you are asking about your class, I do not think so. Unlike C++ you cannot overload operator. Another reason why you cannot do this is objects are pass by reference, meaning

MyClass myObject = <someValue>;

<someValue> is not copied to memory where myObject lives, instead reference (address of) it is. Thus, you need to have new myObject().

One disclaimer you can do this:

MyClass objA = new MyClass();
MyClass objB = objA;

but it is still copying reference not the actual values from myObj.

OP please read this.

While I think from some aspect this question is duplicate of this, I think the levels of knowledge between OPs of these questions is so far apart that I am not going to flag it.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement