Java Objects Basics

Java Objects
A simple C++ object or C struct definition such as "Button b;" allocates memory on the stack for a Button object and makes b refer to it. By contrast, you must specifically instantiate Java objects with the new operator. For example,
// Java code
void foo() {
// define a reference to a Button; init to null
Button b;
// allocate space for a Button, b points to it
b = new Button("OK");
int i = 2;
}
As the accompanying figure shows, this code places a reference b to the Button object on the stack and allocates memory for the new object on the heap. The equivalent C++ and C statements that would allocate memory on the heap
would be:
// C++ code
Button *b = NULL; // declare a new Button pointer
b = new Button("OK"); // point it to a new Button
/* C code */
Button *b = NULL; /* declare a new Button pointer */
b = calloc(1, sizeof(Button)); /* allocate space for a Button */
init(b, "OK"); /* something like this to init b */
All Java objects reside on the heap; there are no objects stored on the stack. Storing objects on the heap does not cause potential memory leakage problems because of garbage collection.

Each Java primitive type has an equivalent object type, e.g., Integer, Byte, Float, Double. These primitive types are provided in addition to object types purely for efficiency. An int is much more efficient than an Integer.

  © Free Blogger Templates Modic Template by For more Information : click Here

Back to TOP