Reputation: 2328
When creating 2 objects of the same type, will the handle from the stack memory point to the same object in the heap or will it point to 2 separate objects. For clarity here is the specific question...
class Q2 {
private static int num = 0;
private String prefix;
public Q2 (String p)
{ prefix = p; }
public String Msg (String str) {
String n;
num++;
n = num.ToString();
return n + " - " + prefix + str;
}
}
Using an appropriate diagram, describe the state of memory after all of the following statements have been executed.
Q2 var1, var2;
var1 = new Q2("Question 2");
var2 = new Q2 ("Another view");
Here are the answers I cannot decide between:
1 object:
2 objects:
Upvotes: 6
Views: 3552
Reputation: 8049
To help clarify the discussion on the heaps here, there are about 8 different heaps that the CLR uses:
HTH
Upvotes: 4
Reputation: 6890
You are using the new
keyword to instantiate objects in two separate variables, so, this always creates new object on the heap. So the answer would be that it will always point to two separate objects.
EDIT:
Static variables such as num
are stored in a special area on the heap called High Frequency Heap, that is not being collected by the garbage collector etc.
Upvotes: 3
Reputation: 11014
Only one copy of a static member exists, regardless of how many instances of the class are created.
So, because your class is non-static, you will end up with multiple instances of your class, but they will refer to the same, single, shared, static member instance.
Note: You should be VERY careful with code like the above because you can end up with multiple class instances altering the value of the shared static member which can result in unforeseen behavior, race conditions, corruptions, etc.
If your intent is for the class to be a shared singleton, then mark the class itself as static so that you only ever have one in your heap at any one time.
Upvotes: 2