Declaring Objects

As just explained, when you create a class. you are creating a new data type. You can
use this type to declare objects of that type. However, obtaining objects of a class is a
two-step process. First, you must declare a variable of the class type. This variable does not define an object. Instead, it is simply a variable ‘that-can refer to an object. Second,you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the new operator. The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns a reference to it. This reference is  more or less, the address’ in memory of the object allocated by new. This reference ‘is then stored the variable. Thus, in Java, all class objects must be dynamically  Let’s look at the details of this procedure. In the. preceding sample programs, a line similar to the following is used to declare
object  type Box.

The first line declares my box as a reference to an object of type Box. After this line executes,  contains the value null, which Indicates that it does not yet point to an actual object, Any attempt to use my box at this point will result in a compile-time error The next allocates an actual object and assigns’a reference. to,it to m my box. After the second line executes, you cause my box as if it were a Box object. But in . reality my box simply holds the memory address of the actual Box object. The effect  of these  lines of code is depicted .

‘(hose renders familiar with C/C++  probably noticed that object references appear 19 lie similar to pointers. This suspicion is, essentially correct. An object reference is similar to n men/on) pointer. The main difference to Java’s safety-is that you cannot manipulate references as Jail pointers: Thus, you cannot cause nil object reference to point to nil arbitrary memory location or manipulate it like nil integer.

[vfb id=1]

Share This