forked from disha2sinha/Object-Oriented-Programming-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObject_Storage.txt
53 lines (38 loc) · 1.25 KB
/
Object_Storage.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be allocated memory either on Stack or on Heap. In C++, when we allocate the object using new(), the object is allocated on Heap, otherwise on Stack if not global or static.
In Java, when we only declare a variable of a class type, only a reference is created (memory is not allocated for the object). To allocate memory to an object, we must use new(). So the object is always allocated memory on heap.
for example:
class Test {
// class contents
void show()
{
System.out.println("Test::show() called");
}
}
public class Main {
// Driver Code
public static void main(String[] args)
{
Test t;
// Error here because t
// is not initialzed
t.show();
}
}
Correct Code:
class Test {
// class contents
void show()
{
System.out.println("Test::show() called");
}
}
public class Main {
// Driver Code
public static void main(String[] args)
{
// all objects are dynamically
// allocated
Test t = new Test();
t.show(); // No error
}
}