开发者

java dynamic memory allocation?

开发者 https://www.devze.com 2022-12-24 17:47 出处:网络
Why is an object initialization using the new keyword called dynamic memory allocation, since compile time 开发者_开发技巧itself we need to know the memory needed for that object.

Why is an object initialization using the new keyword called dynamic memory allocation, since compile time 开发者_开发技巧itself we need to know the memory needed for that object.

Also please explain what happens when you do ClassA object = new ClassA(); in heap and stack .


All Java objects are dynamically allocated. You're always passing around references to them. This is how the language is designed. When you do:

ClassA obj = new ClassA();

Then the object is allocated on the heap and a reference to it is stored on the stack (assuming that's inside a method, of course). What this means is that you can always pass objects about without worrying about where they are stored.


It's dynamic since you don't know when it needs allocating - you allocate upon demand.

Note also that you know how much memory that object requires, but not how much that object's members require. This may only be determinable at run time (e.g. an array of variable size).


If you have a class of JMath and you want to get all its objects on runtime(Dynamically allocation) then you just wrote

ArrayList<JMath> J = new ArrayList<JMath> ();
0

精彩评论

暂无评论...
验证码 换一张
取 消