Creating and Using Objects

Team-Fly

Most of the work in Java programming is done with objects. This work includes creating the object, using both the variables and the methods of that object, and finally, destroying the object when it is no longer needed.

Instantiating an Object

You can create an object simply by telling the Java program the type of object and its name, as shown here:

// Example of creation of an object using "type name" Rectangle myrec;

The preceding example does not declare an object, but simply says that the variable myrec is a reference to an object of type Rectangle. This approach is very similar to the declaration of a pointer in the C language because the variable does not point to any specific object. Java is rather strict about the use of objects, though, so before you can use the variable myrec, you need to assign it to a real object. In Java the primary way to assign a variable to a real object is through Java's 'new' operator, as shown next.

Rectangle myrec; myrec = new Rectangle(0,0,100,200);

This operator does the job of creating the object. New allocates the memory for the object and calls the constructor for the class from which the object is being created. Constructors are covered in more detail later in this chapter in the context of classes, but the point to remember here is that you can pass variables to the constructor through variables included between the parentheses.

Usually, the creation of the reference to the object and the allocation of this reference to an actual object is done in one line, as shown in the following examples:

Rectangle myrec = new Rectangle(0,0,100,100); Random rand1 = new Random();

Declaring arrays of objects is similar to declaring primitive objects. To make an array of a certain object, first you need to make an array of references and then point each of these references to objects. The following code segment demonstrates this technique.

// Example of declaration of an Array of Objects Rectangle[] manyrec = new Rectangle[5]; for (int i = 0; i < 5; i++ ) {     manyrec[I] = new Rectangle(); }
Note 

You can determine the class of any object by using the getClass method that is available to all objects. If the object name is tempobj, its class can be determined as follows:

String name = tempobj.getClass().getName();
System.out.println("Class is:" + name);

That pretty much covers the creation of objects. As Chapter 6 points out, objects comprise two parts: variables and methods. Now that you have created an object, you are ready to learn how to access and use these parts of the object.

Using an Object's Variables

An object's variables are declared in the class definition and are accessed through the object by using the dot notation. For example, the class Rectangle has four member variables: height, width, x, and y. These variables can be accessed as follows:

myrec.height = 10; myrec.width = 200; System.out.println("the x coordinate is " + myrec.x = 10); Myrec.y = 20;

From this example you can see that you can do both the assignment and display of the variables through the dot operator. Even if you have compound objects (objects within other objects), the dot notation is still used to access the inner object's variables and is evaluated from left to right, as shown here:

outobject.innerobject.variable = 5;

Remember that the new operator creates a reference to an object, and an object's variable is also an object itself (either a primitive like int or an object that is more complex). You can therefore create new instances (or objects) of the variables of an object, as shown in this example:

myheight = new Rectangle().height;

Using an Object's Methods

The second part of an object consists of the methods associated with it. Methods are pieces of code that the object can use; they are accessed the same way that variables are, through the dot notation.

object.method(arguments)
Note 

Note that parentheses are required; if no arguments are to be passed to the method, just use empty parentheses.

Examples of method calls follow:

int x; int y; y = 5; TextArea text1 = new TextArea(); text1.setrows(y); x = text1.getrows();

Java is very fussy about the arguments that are passed into methods because in Java you can have different code for the same method; the code that is executed is based on the arguments that are passed into the method. Take, for example, the String class and its method indexOf.

indexOf(int) indexOf(int,int) indexOf(String) indexOf(String,int)

When the Java compiler encounters the indexOf method of an object that references the String class, the compiler evaluates the arguments to see which piece of code to execute. It is therefore important for you to use the correct types of arguments whenever you call a method. If a method requires a float, the Java compiler responds with an error if you try to send an int value to the method.

You can pass a variable of an incorrect type to a method using a process called casting. In casting you take an existing object and create a new value of a different type. Casting can take on three forms:

  • Casting between primitive types such as integers and floats

  • Casting between objects

  • Casting between primitives and objects

When casting with primitives, you must take care as to the precision of the resulting value. A general rule of thumb is that if you cast from a smaller type to a larger type, the precision of the value is retained. However, if you cast from a larger to a smaller value, that is, from a double to a float, then you may experience a loss in the precision of your value. Thus, Java allows you to do implicit casting if you are casting to a larger type and insists that you do explicit casting if you are casting to a smaller data type. Explicit casting between primitive types is accomplished by declaring the destination type in parentheses followed by the variable or expression that you want to cast. Examples of casting between primitive data types are as follows:

int x; long y; y = x;     // no cast needed since Y is a larger data type x = (int)y;  // explicit casting is required here

Compared with casting between primitives, casting between objects is a bit more complicated. In general, you can cast between objects only if they are related by inheritance. Take care when casting from a subclass to a superior class; the subclass will have information that is not contained in the superior class, and a loss of data or precision may result. As with primitive object type casting, you can use implicit casting if you are casting a subclass to a superior class, but you must use explicit casting if you go from a superior class to a subordinate one.

Note 

Boolean data types cannot be used in a cast. They must always be either true or false.

Note 

You can find out whether an object is related to another object by using the Java operator instanceof as shown here:

if (obj1 instanceof Class1) {     Class1 obj2 = (Class1)obj1; }

The last type of casting is when you want to cast a primitive to an object, or vice versa. Java does not really allow this procedure; however, you are allowed to convert the primitive to an object (or vice versa) and then perform the casting. This step is accomplished by using the classes in Java that have the same name as the primitive data type, except that the first letter is capitalized (for example, int data type and Int class).

Certain methods associated with these primitive classes allow for the conversion of values to primitive data types. In the following example, for instance, you have a String object that contains a number, and you want to put this number into a variable of type int.

int  tempvar; String tempstr = "-3456"; tempvar = Integer.parsInt(tempstr);

Garbage Collection

One of the nice features about Java is that you do not have to worry about cleaning up objects after you are finished using them. The Java run-time environment will delete an object upon determining that it is no longer being used. This process is called garbage collection. Garbage collection is performed on a periodic basis and can also be called by using the System.gc() method. You normally do not need to start this process, but you may want to do so if you are going into a memory-intensive routine. You can also force an object to be collected by assigning it a value of NULL.


Team-Fly


Java & BAPI Technology for SAP
Java & BAPI Technology for SAP
ISBN: 761523057
EAN: N/A
Year: 1998
Pages: 199

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net