E
E
EmmGold2016-01-08 21:06:07
Java
EmmGold, 2016-01-08 21:06:07

Is creating an instance of a class equivalent to creating a variable?

Let's say. There is a certain class, I want to create an instance of this class. I write
man superman = new man();
After all, in fact, I create a link to the newly created variable (structure (class)).
It turns out something like
int x = new int(); Looks a bit original...
Why can't I just write "man superman;" ? So it is clear that a new instance of the man class is being created.
Or this entry "man superman = new man();" Are there any interesting features that I don't understand yet? Maybe Java gurus will tell you how else you can use the class description and create class instances.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
K
Konstantin Malyarov, 2016-01-08
@EmmGold

Look:
You have two Superman figurines.
man superman1 = new man();
man superman2 = new man();
The variable superman1 refers to the first figurine, superman2 to the second figurine.
man superman3 = superman1;
Now, we have a third variable that refers to the first figurine.
Total: 3 variables, 2 objects.
Why do we write int x = 0; not int x = new int(0);
Because int is an integer digit and no properties/arguments can be passed to it. One is one, two is two.
man superman1 = new man(run fast, invincible);
man superman2 = new man(jump far, immortal);
int x = new int(0); that's it, the int type has run out of super abilities, only a number and that's it.
String str = new String("String"); just a line, nothing else.

F
FoxInSox, 2016-01-08
@FoxInSox

Why can't I just write "man superman;" ?

Because there are about a million cases where you need to declare a variable but not create an instance.

T
tasce, 2016-01-08
@tasce

Such syntax, but no sugar was invented for it. It remains either to accept, or to come up with a Java preprocessor for sugar. Your example with "man superman;" more like sugar.

A
Alexander Dorofeev, 2016-01-08
@TechCloud

As far as I understand you are new to Java.
I recommend reading this article to get started.
And in general, it’s better to master 4 chapters from this book (you can easily find it on the net). It’s impossible to explain it right off the bat.
In Java Object object;, this is just a reference. You simply declare a variable. To assign an object to it in the Heap (a special data structure that stores all JVM objects), we use object = new Object();
this approach to dynamically change objects, use polymorphism, lazy initialization, etc. d.
Ps
int x = new int(); cannot be written because int is a primitive type.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question