Objects


As we previously noted, Java is an object-oriented language. An object is simply an instance of a class. From now on in this book we will use the term object but keep in mind that an object is a class instance. Every object will have its own copy of the fields declared by its class and can access the methods declared in the class. There are two steps to creating an object. You must first declare a reference type variable of the desired type. Writing the class name followed by the variable name performs this declaration.

 class_name variable_name; 

After the variable is declared, you then allocate memory for the object on the heap using the new operator and create the object by calling one of the class constructors.

 variable_name = new class_name(input_arguments); 

The new operator dynamically allocates memory for the object on the heap at runtime. The two steps for creating an object can be combined into a single executable statement ”

 class_name variable_name =              new class_name(input_arguments); 

You can create an object without associating it with a variable by just using the allocation and initialization syntax. For instance, to add an unnamed Integer object to a collection stored in a Vector , you might type the following ”

 Vector numPoints = new Vector(); numPoints.addElement(new Integer(5)); 

In this code snippet, a Vector object is created using the full declaration-initialization syntax. The addElement() method of the numPoints Vector object is called to load an Integer object into the first storage position of the Vector ( Integer objects are used to represent an integer as a reference type variable). We don't need to save a reference to the Integer object, so we simply create one as an argument to the addElement() method using the new Integer(5) syntax.

The Java API also defines many methods that will return an instance of a class. This is another way in which you can create objects.

Example: Creating Objects

This example demonstrates two ways to create an object. A Date object is created using the new keyword and calling a Date class constructor. A String object is obtained by declaring a String variable and assigning to it the return value of the toString() method, which is the reference to the String created by the method.

 import java.util.*; public class CreateDemo {    public static void main(String args[]) {       Date today = new Date();       String time = today.toString();       System.out.println("The time is "+time);    } } 

Output (will vary) ”

 The time is Fri Aug 02 10:00:38 GMT-07:00 2002 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

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