< Zurück | Inhalt | Weiter >

3.2.2 Object Types

The real power in Java, or any object-oriented language, comes not from the scalar types, cool operators, or powerful control statements it provides (see below), but from its objects.

Object-oriented programming is a relatively recent innovation in software design and development. Objects are meant to embody the real world in a more natural way; they give us a way to describe, in our programs, the real-world objects with which we deal. If you are programming a business application, think of real-world business objects such as orders, customers, employees,


addresses, and so on. Java is an object-oriented programming language and thus has some significant syntax related to OO concepts.

If you are new to object-oriented programming, be sure to read Chapter 1 of Eckel’s Thinking in Java.

In Java, we define a class to represent the objects about which we want to program. A class consists of the data and the methods to operate on that data. When we create a new instance of some class, that instance is an object of that type of class. Example 3.5 shows a simple class.



image

Example 3.5 Simple class

class PairInt

{

// data int i; int j;


// constructors PairInt() { i=0; j=0; }

PairInt(int ival, int jval) { i=ival; j=jval; }


// methods

setI(int val) { i=val; } setJ(int val) { j=val; } int getI() { return i; } int getJ() { return j; }

}


image


Note that this class defines both data (i, j) and methods (setI(), getJ(), and so on). We put all this into a file named PairInt.java to match the name of the class definition.

If some other Java code wanted to create and use a PairInt object, it would create it with the new keyword followed by a call to a constructor (Example 3.6).

This example shows only a snippet of code, not the entire PairInt class. That class, though, would likely reside in its own source file (named for its class name). In Java you normally create lots of files, one for each class. When it’s


image

Example 3.6 Using simple class

// declare a reference to one: PairInt twovals;


// now create one:

twovals = new PairInt(5, 4);


// we can also declare and create in one step: PairInt twothers = new PairInt(7, 11);


image


time to run the program, its various classes are loaded as needed. We’ll discuss grouping classes together and how Java locates them in Section 3.3.1.

In Java, each source file contains one class and the file is named after that class. It is possible to define inner classes located inside another class definition and thus inside its file, but that introduces other complexities that we wish to avoid discussing at this point. Most importantly, an inner class has access to even the private members of the enclosing class. (Read more about inner classes in any of the Java books that we recommend at the end of this chapter.)

For each of the class methods, class data declarations, and the class itself, Java has syntax to limit the scope, or visibility, of those pieces. The examples above didn’t include those keywords—that is, they took the default values. Usually you’ll want to specify something. See Section 3.4.1.


3.2.2.1 Objects as References

So far we have not explained something important about object type variables. These variables can all be thought of as pointers or references to an object. When you declare a variable of an object type, what you are declaring is a vari- able that is capable of referring to an object of that type. When declared, it does not point at anything. It has a value of null and any attempt to use it will result in a null pointer exception (more on those later).

Before an object variable might be used, it must be made to refer to an instance of an object. This is done by assignment. You can assign an existing object, or you can use the new operator.

Any new class will have a constructor, that is, a method whose name is the

name of the class. There can be many different constructors for the same class,


each with unique types of parameters. For example, the String class has many different constructors, including one which constructs a new String from a different String and another that constructs a new String from an array of bytes.


String strbystr = new String(oldstr); String strbyarr = new String(myByteArray);


3.2.2.2 Strings

One of the most commonly used classes is the String class. It comes already defined as part of Java and has some special syntax for initialization which makes it look familiar. Whereas other objects need a new keyword and a con- structor call, a String object can be created and initialized with the intuitive double quotes, as in:


String xyz="this is the stringtext";


The compiler also makes a special allowance for Strings with respect to the plus sign (+). It can be used to concatenate two Strings into a third, new String.


String phrase = "That is"

String fullsent = phrase + " all.";


It is worth noting that Strings do not change—they are immutable. When you assign a String the value of one String plus another, there’s a lot of String object creation going on behind the scenes. If you need to do a lot of concatenation of Strings, say inside loops, then you should look into the use of the StringBuffer object. See Appendix A of Thinking in Java, 3rd ed., the section titled Overloading “+” and the StringBuffer, for a full discussion of the tradeoffs here.

There are a variety of methods for String—ones that will let you make substrings, search for substrings at the start or end or anywhere in the string, or check for equality of two strings.

Table 3.2 shows some of the most useful methods associated with String

objects.


Table 3.2 Useful String methods


image

image

Return type


int


boolean


boolean


String


String


boolean


boolean


String

Method


length()


equals(Object obj)


equalsIgnoreCase(String str)


toLowerCase()


toUpperCase()


startsWith(String substr)


endsWith(String substr)


substring(int index)

Description

Returns the length, i.e. number of characters, in the String.

Returns true if the object is a String object and is equal to the String. (Aside: the argument takes a generic Object type rather than only a String object because it’s meant to override the equals() method in the class Object of which String is a descendant.) This is the way to compare two Strings to see if they are both holding the same sequence of characters. Using stringA

== stringB will only tell you if stringA and stringB are referencing the same object (pointing to the same location in memory). What you typically want is stringA.equals(stringB).

Similar to equals(), but this one only allows a String parameter, and it ignores the upper/lower case distinction between letters. For example:

String sample = "abcdefg"; String sample2 = "AbCdEfG"; sample.equalsIgnoreCase(sample2)

returns true.

Returns a string with all characters converted to lowercase.

Returns a string with all characters converted to uppercase.

Returns true if the String starts with the given substring.

Returns true if the String ends with the given substring.

Returns a string starting at position index

to the end of the String.


image


Table 3.2 (Continued)


image

image

Return type


String

Method


substring(int first, int last)

Description

Returns a string starting at position first and up to, but not including, character position last. If last is greater than the length of the String, or last is less than first, it throws an IndexOutOfBounds exception.


image


3.2.2.3 Other Classes: Reading Javadoc

Java comes with a huge collection of existing classes for you to use. The simplest ones are just wrappers for the primitive classes. There is an int primitive data type, but Java provides an Integer class, so that you can have an integer as an object. Similarly, there are classes for Long, Float, Boolean, and so on. Such classes aren’t nearly as interesting as the myriad other classes that come with Java. These others provide objects for doing I/O, networking, 2D and 3D graphics, graphical user interfaces (GUIs), and distributed computing. Java provides ready-to-use classes for strings, math functions, and for special kinds of data structures like trees and sets and hash tables. There are classes to help you with the manipulation of HTML, XML, and SQL, as well as classes for sound, music, and video. All these objects can be yours to use and enjoy if you just learn the magic of reading Javadoc—online documentation for Java classes. The documentation for all these classes is viewed with a Web browser. (In a following chapter we’ll describe how you can make Javadoc documents for the classes that you write, too.)

The online version of the API documentation can be found at


http://java.sun.com/j2se/1.4.2/docs/api/


for Java 1.4.2. (Similarly, put 1.5.1 or whatever version you want at the appropriate place in the URL.) When displayed, it shows a three-frame page, as seen in Figure 3.1, except that we’ve overlaid the image with three labels: A, B, and C.

The upper left frame of the Javadoc display, the area labeled with A in our figure, lists all the packages that are part of Java 2 Standard Edition (J2SE). While there are many other packages of classes available for Java, these classes are the standard ones available without any other class libraries, with no


image

A

C


B



d


Figure 3.1 The three frames of a Javadoc page


additional downloads necessary. Other classes are documented in the same way—with Javadoc—but they are downloaded and displayed separately.

Frame B initially lists all the classes and interfaces available in all of the packages. When you select a package in A, B will display only those interfaces and classes that are part of the chosen package.

Frame C starts out with a list and description of all packages. Once you have selected a package in A, C will show the overview of that package, showing its classes and interfaces with descriptions.

But C is most often used to display the detailed description of a class. Choose a class or interface in B and you will see C filled with its descrip- tion—some opening information followed by a list of the visible members of that class, followed by the possible constructors for that class and all the meth- ods in that class (Figure 3.2). Each method is shown with its parameters and a one-sentence description. Clicking on the method name will open a fuller description (Figure 3.3).



image


Figure 3.2 Javadoc display of class information


image

Figure 3.3 Javadoc display of a single method


Since you will likely be referencing the Javadoc pages regularly, you may want to download a copy to your hard drive. From the same page on the java.sun.com Web site where you can download the Java SDK you can also download the API documentation.

If you agree to the licensing terms, you will download a large ZIP file. In- stalling the documentation, then, is just a matter of unzipping the file—but it’s best if you put it in a sensible location. If you have installed your Java SDK into a location like /usr/local/java then cd into that directory and unzip the file that you downloaded. Assuming that you saved the downloaded file into /tmp, a good place to put temporary files, and assuming that you have in- stalled your version of Java into /usr/local/java and that you have write


permission in that directory (check the permissions with ls -ld .) then you can run these commands:


$ cd /usr/local/java

$ unzip -q /tmp/j2sdk-1_4_2-doc.zip


There may be quite a pause (tens of seconds) while it unzips everything. The unzip command will spew out a huge list of filenames as it unpacks them unless you use the -q option (“quiet”) on the command line (which we did, to avoid all that). The files are all unzipped into a directory named docs. So now you can point your browser to


file:///usr/local/java/docs/api/index.php


Now you have your own local copy for quick reference, regardless of how busy the network or Sun’s Web site gets. Be sure to bookmark this page; you’ll want to reference it often. It’s your best source of information about all the standard Java2 classes.