Reputation: 23
I'm in a-level computing and I was wondering if someone could please tell me the definition of this. If I have a class with methods etc, then I make another class where I kind of generate a variable of that first class. What is this actually called? It's the variable definition I'm after shown below "whatisThis" is this a class object?
MyClass1
{
...
}
MyClass2
{
MyClass1 whatisThis = new MyClass1();
}
Upvotes: 2
Views: 281
Reputation: 11026
Structurally:
class ClassName
{
//... class/object level member variables can be here (also called fields)
void MethodName()
{
//... method level variables can be here (also called local variables)
}
//... class/object level member variables can be here (also called fields)
}
Is the member variable class or object level ?
static
modifierstatic
modifierSo in the definition of the class MyClass2 you've got one object level member variable with name whatisThis
and with type MyClass1
. (It is object level variable, because there is no static
keyword)
Now to the definition of the variable itself. Let's divide this definition into 3 parts:
MyClass1 whatisThis = new MyClass1();
MyClass1 whatisThis
MyClass1
, this is the type name, same as int
in int i;
whatisThis
, this is the variable name, same as i
in int i;
=
new MyClass1()
MyClass1
Also, let's define, what is happening in memory, when the line is executed (this line is only executed, when MyClass2
gets instantiated):
MyClass1 whatisThis
=
MyClass1
type object in the heapnew MyClass1()
MyClass1
is instantiated in the heapSo the final answer is:
In the class MyClass2
, you are defining the object-level variable whatisThis
of type MyClass1
and you are initializing it with reference to object instance of type MyClass1
that is instantiated on heap.
Upvotes: 1
Reputation: 1062630
That is an instance field that is initialized to a new instance; encapsulation of a MyClass1
would be my description. If you were re-exposing an interface common to both types, then, it might be decoration.
Of course, with no methods, a private field can't do a lot ;p
So to clarify:
whatisThis
is a field (private
and per-instance, in this case) of type MyClass1
new MyClass1()
is a new object of type MyClass1
whatisThis
during construction; field initializers (to use the name of this assignment) typically happen before any custom constructors are invokedUpvotes: 2
Reputation: 69988
What is this actually called?
You are declaring a new object of MyClass1
with operator new
(which allocates memory for the object)
"whatisThis" is this a class object?
Yes
Upvotes: 0
Reputation: 131789
That's just what it looks like - a member variable, and additionally it gets directly initialized. It isn't any different from primitive types like int
and the likes. You can use it at your will inside of your MyClass2
.
Upvotes: 1