`
`Master the art of
`c eating distributed
`Internet programs
`
`Create your own
`p werlul agent -server
`applications
`
`U e the Java source code
`and programming tools to
`create portable Java
`
`John Rodlev
`
`APPLETS
`
`TM
`
`CORIO LIS
`GROUP
`BOOKS
`
`Starbucks Corp. Exhibit 1021
`
`
`
`Applets have the Web world all shook up!
`Java applets are already animating Web
`pages all over the world, but animations
`aren't all that Java can do. From forms to
`games, Java applets embedded in your Web
`pages give you unprecedented two-way
`communication with your visitors.
`
`TM
`
`Writing java Applets is the book that gives you the most in-depth, practical techniques for creating
`applets that sizzle! You'll learn how to create everything from a simple Web-page animation to a
`sophisticated "agent" applet that can go out and search the Net! In this book, you'll:
`• Walk step-by-step through the process of applet development
`• Find crisp coverage of the basics of Java programming ·
`• Learn how to turn the Web inside out with a Java-based agent syste~ontrolled
`by a Java applet
`• Discover how to add animation and special effects to your Java applets
`• Create applets that work around the security limitations placed on them by Java
`• Load images, applets, and classes across the Net
`• Write threaded network communication applets
`• See how browsers control applets, and how you can make the most efficient use of each
`browser's environment
`In Writing java Applets, you'll learn the best of proven applet programming techniques. Combining
`the power of C++ with state-of-the-art extensions, Java is familiar to C++ programmers, yet is easi(cid:173)
`er to learn and much safer for novices. Writing java Applets introduces you to the Java language
`and takes you step by step through the creation and use of Java applets. Along the way you'll get a
`peek beyond applets into a world where independent Java classes traverse the Net by themselves.
`Web and Internet programming has never been easier. Join the revolution today!
`
`THE CORIOLIS GROUP
`7339 E. Acoma Drive, Suite 7
`Scottsdale, AZ 85260 USA
`(602) 483-0192
`http://www.coriolis.com
`
`Shelving: Java/Internet Programming
`I
`ISBNL-883577·78·0
`
`SALE PRICE $7.99
`
`, II 11~1111111/lllll J I~IIIIJ/1,
`
`IU IU\J-' _, • • - -
`
`I 7
`
`Starbucks Corp. Exhibit 1021
`
`
`
`WRITING
`
`APPLETS
`
`John Rodley
`
`~ CORIOLIS GROUP BOOKS
`
`Starbucks Corp. Exhibit 1021
`
`
`
`Publisher
`Editor
`Proofreader
`Cover Design
`Interior Design
`Layout Production
`Indexer
`
`Keith Weiskamp
`Scott Palmer
`Diane Green Cook
`Gary Smith
`Bradley 0. Grannis
`KimEo.ff
`Caroline Parks
`
`Trademarks: Java is a registered trademark of Sun Microsystems, Inc. All other
`brand names and product names included in this book are trademarks, registered
`trademarks, or trade names of their respective holders.
`
`Copyright© 1996 by The Coriolis Group, Inc.
`
`All rights reserved.
`
`Reproduction or translation of any part of this work beyond that permitted by
`section 107 or 108 of the 1976 United States Copyright Act without the written
`permission of the copyright owner is unlawful. Requests for permission or
`further information should be addressed to The Coriolis Group.
`
`The Coriolis Group
`7339 E. Acoma Drive, Suite 7
`Scottsdale, AZ 85260
`Phone: (602) 483-0192
`Fax: (602) 483-0193
`Web address: www.coriolis.com
`
`ISBN 1-883577-78-0 : $39.99
`
`Printed in the United States of America
`
`10 9 8 7 6 5 4 3 2 1
`
`Starbucks Corp. Exhibit 1021
`
`
`
`The Java
`Revolution
`
`java is cool, but why? Take a look at
`the key features, and judge for
`yourse lf.
`
`In its short existence, Java has generated more excitement and more wild specu(cid:173)
`lation than all the other programming languages put together. Some of that is
`simple hype, a result of the fact that the software industry is now a very big
`business, but much of it is quite real. Java is a revolutionary force.
`
`Over the course of this book, we'll develop a large application called the Agent
`system. The Agent system will consist of a small, standalone Java program and a
`bunch ofJava applets. The application will also include a number of smaller Java
`applets to demonstrate particular features of the language. Through the Agent
`system, I'll try not only to illustrate Java programming techniques, but also to
`provide you with a glimpse of the new classes of applets and applications that
`you can write using Java.
`
`Our Agent system will allow Web users to dispatch a program (called an agent)
`to run on each machine in a network oflnternet-connected machines and then
`return its results via the Web. This agent is a Java class. We'll develop a couple of
`basic agents to do things like finding files, but the power of the system, like the
`power of Java, is that by using the base Agent class, users can write their own
`agents to do things limited only by their imagination. The base Agent class and
`the standalone agent server deal entirely with the problem of distributing the
`agent throughout the network.
`T~~Agent system provides a good introduction to Java programming because it
`uuhzes th
`·
`·
`fJ
`l
`ree vanet1es o ava c asses: applets, standalone applications, and classes
`
`3
`
`Starbucks Corp. Exhibit 1021
`
`
`
`4 Chapter 1
`
`that can function in either applet or standalone mode. Over the course of devel(cid:173)
`oping these classes, we'll get to see the possibilities and limitations of each.
`
`that can function in either applet or standalone mode. Over the course of devel(cid:173)
`oping these classes, we'll get to see the possibilities and limitations of each.
`
`But first, let's define what we mean by the term applet. An applet is a small
`program that runs within another, larger, host program, whose purpose is usu(cid:173)
`ally to enhance the functionality of the host program and which could not
`exist without the host program. In Java's case, a Java applet enhances the func(cid:173)
`tionality of a Web browser. A browser can display text, but add an applet and
`you can make that text bounce around the screen like a ping-pong ball. That's
`all we really mean when we talk about an applet-a program that runs within
`a Web browser.
`
`And so, without any further ado, let's look at an applet. Listing 1.1 shows a
`simple example.
`
`Listing 1.1 hello.java Applet
`
`package chapl;
`
`import java.awt.Graphics;
`import java.awt.*;
`import java.applet.Applet;
`
`public class chl _figl extends Applet {
`
`public void paint(Graphics g)
`g.drawString( "Hello world", 20, 50 );
`}
`
`Pretty exciting, eh? We'll get into more details about specific programming tech(cid:173)
`niques later in the book, but the power of that simple nine-line program shows
`
`[aiD Apple! Viewer: chapl/chl_figl.class aaJ
`Apple!
`
`Hello world
`
`apple! started
`
`Figure 1.1
`hello.Java running in Sun's appletviewer.
`
`Starbucks Corp. Exhibit 1021
`
`
`
`you what's possible. For now, let's take a quick look at what makes Java useful in
`the first place.
`
`The Java Revolution S
`
`We're Talking Applet Programming
`One reminder: This book is about Java applet programming,
`not about Java programming in general. If you don't have at
`least a basic grasp of the Java language, development tools,
`and their associated techniques, it will be hard for you to fol-
`low the discussion in this book.
`
`If you need a good introduction to Java, you (really) can't do
`better than The java Programming EXplorer by Neil Bartlett,
`Steve Simkin, and Alex Leslie (Coriolis Group Books, 1996),
`all of whom are leaders in the Java programming community.
`For a good Java language reference, see The java Programming
`Language by Anthony Potts and David Friedel (Coriolis Group
`Books, 1996).
`
`The Power of the Concept
`When people talk about Java, it's not always clear what they're talking about,
`because Java is not just a language. Java is both a language and a set of class
`libraries. Much, if not most, of the power of Java comes from these class li(cid:173)
`braries which, in Java, are known as packages. In that sense, Java is compa(cid:173)
`rable to something like Microsoft Visual C++ with Foundation Classes or
`Borland C++ with its ObjectWindows Library (OWL). Figure 1.2 shows the
`package hierarchy for Java.
`
`Java's revolutionary potential is not due to a single feature of the language but to
`a combination of four features: network awareness, portability, security, and object
`orientation. Some of these features are inherent in the language, while others are
`derived from the class libraries. These features make possible a whole range of
`applications that we could only dream of before Java. Let's examine these fea(cid:173)
`tures in more detail.
`
`Network Awareness
`Java's tight integration with the Internet in general-and with the World Wide
`Web in particular-is the main force driving its explosive growth. Network aware(cid:173)
`ness, as we use the term here, simply means that every provision has been made
`
`-
`
`Starbucks Corp. Exhibit 1021
`
`
`
`6 Chapter 1
`
`applet
`awt
`
`lang
`
`net
`uti I
`
`Figure 1.2
`The Java package hierarchy.
`
`to allow Java applications to incorporate network capability. For the Internet,
`this amounts to providing a low-level socket interface.
`
`The Internet is populated by a bunch of servers, each of which performs a par(cid:173)
`ticular function, such as Telnet, FTP, or handling operations on the Web. Each
`of these servers runs on a machine, listening to a port and waiting for a client to
`connect. Both client and server connect to the network at the lowest level via a
`socket interface. In Java, for instance, a server program running on
`mymachine.com can open a socket and accept calls on it with two lines of code,
`as shown in the following snippet:
`
`ServerSocket MyServerSock =new ServerSocket( 1037 );
`Sockets= MyServerSock.accept();
`
`A client can then connect to mymachine.com with the one line of code shown
`here:
`
`Socket MyClientSocket =new Socket( "mymachine.com". 1037 );
`
`When those two calls return, the two machines are connected and can read and/
`or write to that connection.
`
`Starbucks Corp. Exhibit 1021
`
`
`
`The Java Revolution 7
`
`Dealing with network I/0 at the socket level, while necessary for some applica(cid:173)
`tions, can be very tedious, requiring implementation of whatever protocol you
`intend to use. Fortunately, you can often bypass this step because Java provides
`higher-level classes for such cases. The example in Listing 1.2 manages to down(cid:173)
`load an HTML file, while avoiding the explicit use of sockets entirely.
`
`Listing 1 . 2 Downloading an HTML File
`public class DLHTMLFile extends Applet {
`public void start() {
`try {
`URL u - new URL("http: // www.channell .com/use rs /ajrodley / index .html");
`System.out.println( "u-"+u J:
`try (
`URLConnection uc - u.openConnection();
`InputStream is - uc.getinputStream();
`byte b[]- new byte[is.available(JJ:
`is. read ( b ) ;
`System.out.println( "received byte array "+new String(b,OJJ:
`} catch( IOException e J {System.out.println( "ioex "+e); }
`catch( MalformedURLException el J {System.out .println( "mfuex "+ell;}
`
`In this example, Java's URLConnection class handles connecting to the http
`daemon, which serves HTML files at www.channell.com. The class finds the file
`we want at that server and creates a byte stream that we can read from that file.
`
`The lnputStream handles the rest. What you see when you run this applet is the
`text of my home page printing to the standard output device (or Java console in
`Netscape).
`
`The messages that the client and server exchange once they connect via sockets
`is what Java refers to as content. Examples of content include the GIF and JPG
`graphics formats and the HTML document format. The Java class that deals
`with a particular type of content is known as a content handler.
`
`Suppose that we want to display a GIF file on the screen. What we want to end
`up with in memory is a Java Image object. The process of getting that image in
`memory has three levels:
`
`• The socket connection
`• A stream of GIF-formatted bytes (content) flowing over that connection
`• An Image object created from that GIF-formatted byte stream (by a content
`handler)
`
`Starbucks Corp. Exhibit 1021
`
`
`
`8 Chapter 1
`
`We've seen how Java gives you easy control over the first two levels, but it's the
`last step that is the payoff. For business reasons, Sun has decided not to give
`coders direct access to their image, FTP, and HTML content handlers, although
`the image handlers are useable via the Applet class. This means that content
`handlers will be one area where Netscape and other browsers can provide extra
`value, for which, presumably, users will be willing to pay.
`
`Even with that caveat, Java has taken us a long way toward complete network
`connectivity. And even though its content handlers are inaccessible, Java does
`provide a platform on which to build your own content handlers.
`
`Java's Net-centricity is embodied in the java.net and java.applet packages
`(class libraries). The java. net package supplies the basic classes for dealing
`with URLs and TCP/IP sockets, and java.applet provides Java's link to the
`Web, via the Applet class-a class that allows an application to appear in the
`middle of an HTML document when that document is viewed with a Web
`browser.
`
`The URLs and sockets of java. net are fine building blocks, but it is the concept
`of embedding programs (applets) within HTML documents that makes Java a
`revolutionary force. A browsed Web document is a fairly static item. The text
`just sits there while the user browses through it. Java applets, on the other hand,
`are active items. A Web page with applets can change according to any of a wide
`variety of stimuli. These stimuli can come directly from the user, from other
`applets or processes on the same workstation, or from some process out on the
`Net. They can come from anywhere, and in a manner that is invisible and/or
`indecipherable to the user.
`
`Thus, with applets, you can create a Web page that behaves more like the user
`interface of a traditional application rather than like a regular old HTML page.
`And if you can get the functionality of a traditional application via a Web page,
`why buy traditional applications?
`
`The Internet has physically connected a huge number of machines. Yet, in many
`cases, their only connection to each other are the happy faces they display via
`HTML. With Java, these machines can work together rather than just smiling
`stupidly at one another. Net-connected machines now have a language by which
`they can both request and provide services.
`
`Starbucks Corp. Exhibit 1021
`
`
`
`pzz
`
`The Java Revolution 9
`
`Java Compared to HTML
`HTML is a language and Web browsers are essentially HTML
`interpreters. HTMI.:s sole purpose, however, is to describe static
`text documents. A browser is an intelligent "book," with each
`HTML document serving as an intelligent page. That is
`HTMI.:s limitation: Its central metaphor is "a book of pages,"
`and there are only so many things you can make a book do.
`Java uses an entirely different metaphor: the abstract CPU
`known as the java Virtual Machine QVM).
`
`The JVM is a specification that describes the instruction set
`for an abstract CPU. Every CPU-80486, Pentium,
`PowerPC-has such a specification. An actual CPU imple(cid:173)
`ments that specification in hardware, so you end up with a
`chip that understands instructions from that instruction set.
`
`There is no physical CPU that understands the JVM instruc(cid:173)
`tion set. Instead, Java relies on an interpreter to translate the
`JVM instructions into instructions that the local CPU under(cid:173)
`stands. Thus, for every different CPU and operating system,
`there is a different Java interpreter.
`
`Portability
`Java is a portable language. It achieves this portability by taking a different ap(cid:173)
`proach from that taken by current C and C++ development packages. In C,
`under DOS, you might write a source file called hello.c that looks like this:
`
`int main()
`{
`printf( "hello world\n" J:
`}
`
`The C compiler turns that file into another file, "hello.exe" that is essentially a
`stream ofinstructions from the 80386 instruction set. In fact, if you disassemble
`hello.exe, you see a stream of 386 instructions like those shown in the following
`code snippet:
`
`Starbucks Corp. Exhibit 1021
`
`
`
`10 Chapter 1
`
`PUSH SP
`MDV BP, SP
`
`RET
`
`If you compile the same program on a computer that uses a Motorola 68000
`chip as its CPU, hello.exe would contain a different stream of instructions(cid:173)
`ones that correspond to the 68000's instruction set. When you want to run
`hello.exe, the operating system simply feeds the instruction stream directly to
`the CPU. (I realize that this example is simplified, but it makes the point.)
`
`This approach is very efficient, but it has one drawback: Because different com(cid:173)
`puters use different instruction sets, a compiled program usually will run only
`on the machine for which it was compiled.
`
`The Internet, however, connects computers of many different types. Therefore,
`a Java program must be able to run on all {or at least most) of those computer
`types. The traditional approach of compiling directly to machine code doesn't
`get the job done.
`
`Java takes a different approach. Instead of translating the Java source code di(cid:173)
`rectly into the instruction set of a particular hardware CPU, the Java compiler
`translates it into a bytecode file. This bytecode file contains a stream of instruc(cid:173)
`tions from the instruction set of an imaginary CPU known as the JVM (for
`more information on the JVM, see the Java Note on page 11. These bytecodes
`cannot be fed directly to any real CPU, because no real CPU understands them.
`Instead, a Java interpreter translates those bytecodes into instructions that the
`real CPU understands.
`
`The Java equivalent ofhello.c, hello.java, goes through the steps shown in List(cid:173)
`ings 1.3 through 1.5. Listing 1.3 shows the Java source code file. Listing 1.4
`shows the "compiled" Java file, which consists of bytecodes-machine instruc(cid:173)
`tions for the Java virtual machine. Finally, Listing 1.5 shows how the Java inter(cid:173)
`preter translates the code from Listing 1.4 into instructions for an actual, physical
`CPU. (Listings 1.4 and 1.5, by the way, are illustrative and aren't meant to be
`taken literally. The actual instructions you use might be different.)
`
`Listing 1. 3 hello.java Source File
`public class Hello {
`public static void main() {
`System.out.println( "Hello Java world" );
`}
`
`Starbucks Corp. Exhibit 1021
`
`
`
`The Java Revolution 11
`
`Listing 1.4 Disassembled Bytecode File hello.class
`PUSH STACK
`
`RETURN
`
`When you run hello.class, the Java interpreter turns the bytecodes into a stream
`that looks like the instructions from our compiled hello.exe file, as shown in
`Listing 1. 5.
`
`Listing 1 . 5 Bytecodes Translated into Machine Code
`PUSH SP
`MOV BP, SP
`
`RET
`
`Running the bytecodes through the Java interpreter is an extra step through
`which traditional compiled programs don't go. It is this extra step, however, that
`gives Java its portability, because bytecodes mean the same thing no matter what
`computer they run on. Our hello.class program will, therefore, run on any ma(cid:173)
`chine for which a Java interpreter has been written.
`
`A running Java program thus consists of three pieces: the source file, the bytecode
`file, and the Java interpreter. As I mentioned earlier, the bytecode file is very
`similar to the traditional executable in that it contains a stream of machine in(cid:173)
`structions. The difference is that those machine instructions don't work on any
`particular physical CPU; they only make sense to the Java interpreter.
`
`This approach to portability is not new. UCSD Pascal enjoyed a brief moment
`in the sun back in the late 1970s with its implementation of a bytecode inter(cid:173)
`preter. Unfortunately, it was ahead of its time. The market demand for portable
`applications was overwhelmed by the demand for the kind of high-performance
`applications that C could provide.
`
`Java's portability is not especially cheap, however. In order to achieve it, some(cid:173)
`one has to "port" the Java interpreter to each of the platforms on which Java
`runs. Unfortunately, a huge portion, if not a majority, of the functionality of
`Java is contained in native methods-dynamic link libraries that are compiled
`to native machine code. Many of these native methods use native C++ class
`libraries that have been built up over the years, such as Microsoft Foundation
`classes. So when you hear Java enthusiasts, myself included, opining as to how
`Java will replace C++, just remember that for the current generation of hard-
`
`Starbucks Corp. Exhibit 1021
`
`
`
`12 Chapter 1
`
`ware, Java rests on a foundation of C++ code. This will change only when ma(cid:173)
`chines that support the JVM instruction set begin to appear.
`
`Security
`Up to now, we've talked mainly about the rewards of Javability, the gold-paved
`streets of Java world. As with every potential reward, there is also an element of
`risk, and in Java world, much of that risk involves security.
`
`How secure is Java? The short answer is "pretty secure." For many of us, that
`answer is just not good enough. What does security mean to Java and why should
`we worry about it? It's probably better to start with what isn't secure under Java.
`Java's network awareness, for example, is simply a product of existing network
`protocols: http, ftp, and gopher. Java's network communications are no more or
`less secure than these underlying protocols. Java does not encrypt, although that
`doesn't mean you can't do it yoursel£ It's just not part of the language. What this
`. means is that if someone breaks one of these protocols, any Java application
`using those protocols is also broken.
`
`Running Java applets via the Web does open a huge security hole for a whole
`class of machines that never had to worry about security before. In the bad old
`days of dial-up bulletin boards (pre-1993), a pretty reliable rule of safe comput(cid:173)
`ing was "never run anything downloaded from a bulletin board." Especially in
`the Mac world, computer viruses were as common as the cold virus is among
`humans, and the easiest way to catch one was to run something you found on
`the Net. Now, Java postulates a world where running downloaded executables is
`the basic computing activity.
`
`The question is one of risk/reward. For a single user running a Web browser for
`education and entertainment, the risks of unsecure network computing are fairly
`small. Even in the worst case, a downloaded virus wipes out the user's machine;
`it's only one machine, the work-product of one person. A painful loss, but in
`absolute terms, fairly small.
`
`The risks multiply exponentially when you start talking about corporate com(cid:173)
`puting. Large-scale corporate computing lurks somewhere in the background of
`almost every human activity. When the machines that make up this underlying
`base of computing power start running executables that have been passed, un(cid:173)
`verified, from one machine to another, the public danger posed by a malignant
`executable is limited only by the imagination of its inventor.
`
`Starbucks Corp. Exhibit 1021
`
`
`
`The Java Revolution 13
`
`Thus, for many security-conscious applications, the migration to Java world
`requires a leap of faith equivalent to the one the Pilgrims took when they left
`England for North America. What kind of protection can Java offer the
`security conscious?
`
`Memory Segmentation
`Internally, Java maintains two separate memory sections: one section that the
`Java interpreter uses for itself, and one section that it uses to satisfy the needs of
`Java applets. An applet cannot, via Java itself, access memory from the Java seg(cid:173)
`ment. This is a product both of internal security measures andJavis pointer-less
`design. It would be nearly impossible to get this kind of protection in a language
`that supported pointers.
`
`Java relies on the native operating system to protect it from malicious external
`applications. All of the operating systems that Java runs on enforce some system
`whereby the memory of one application, in this case, the Java applet, is auto(cid:173)
`matically protected from the code of any other application. Java's immunity to
`this kind of malicious external attack is largely dependent on the native OS.
`
`Native Methods
`Some large proportion ofJavas security risk is embodied in the ability of applets to
`get "outside" of Java via native methods and native executable calls. Java allows
`applets to call out to dynamic link libraries and executables that are assumed al(cid:173)
`ready to exist on the workstation. As far as Java is concerned, these native methods
`and executables are completely unsecure-they can be written in any language, by
`anyone, for any purpose, malicious or otherwise. This may sound like a fatal weak(cid:173)
`ness, but it really isn't. While Java does not protect you from malicious native
`methods, it doesn't offer native method virus writers any help, either.
`
`While Java classes are downloaded over the Net as a basic operating procedure,
`native methods and executables are not. A native method must already exist on
`a computer in order for a Java applet to execute it. It does not get downloaded.
`This means that it is as difficult to distribute a native-method virus as it has
`always been to distribute regular viruses. Native methods, malignant or not, do
`not appear automatically on a user's workstation in the way that Java classes do.
`Individual users must be convinced to load them on their workstations, one at a
`time. Thus, distributed attack via a native method is unworkable. The risk of a
`successful, large-scale attack via the Java distributed computing mechanism is
`entirely contained within Java itself
`
`Starbucks Corp. Exhibit 1021
`
`
`
`l
`
`14 Chapter 1
`
`Access to System Resources via Java
`System resources-the network, the file system, and so on-are the ultimate
`target of spies and virus writers. Programmatic access to them is dangerous, but
`to completely eliminate that access would be a crippling burden on any lan(cid:173)
`guage. Java deals with this security/functionality tradeoff by funnelling all po(cid:173)
`tentially dangerous system resource access requests through the Java
`SecurityManager class.
`
`The SecurityManager class allows the browser to manage applets' access to sys(cid:173)
`tem resources. The Security Manager is like a moat between the system resources
`and the horde of barbarian applets. The browser can choose to fill that moat
`with obstacles and barbed wire, or it can pave over the moat, allowing applets
`"the run of the castle." We'll discuss the SecurityManager class in more detail in
`Chapter 10.
`
`The first crop of browsers have mostly chosen to cop out on the security ques(cid:173)
`tion by putting the burden on the user. HotJava, for instance, allows the user to
`configure network and file 110 access through an options dialog box.
`
`There is no "solution" to this part of the security problem. You must provide
`access to system resources to allow applets to get anything done, but providing
`that access opens the system to attack. The SecurityManager provides a work(cid:173)
`able solution by allowing browsers to validate that access before granting or
`denying it.
`
`Java is neither secure nor unsecure. Security, like the common cold, is actually a
`number of problems, some of which are solvable, some of which are not. Java's
`overall approach to security is to deal with the solvable security issues automati(cid:173)
`cally, and provide the user/browser with a way, via the SecurityManager, to gain
`protection from the rest. This strategy is the only reasonable one. Only time will
`tell if Java's execution of the strategy has been successful.
`
`Object Orientation
`The term object orientation has been applied so indiscriminately that only man(cid:173)
`agers still think it means anything. This is unfortunate because Java, combined
`with the Internet, has the potential to start fulfilling some of the dreams that
`have long driven object-oriented designers.
`
`There are two basic concepts behind all definitions of object orientation: inher(cid:173)
`itance and encapsulation. Inheritance is based on the notion that many objects
`
`Starbucks Corp. Exhibit 1021
`
`
`
`will be modified versions of existing objects. Inheritance says that if one object
`inherits another, it gets all the functionality of that object. So, in Java, if we say
`something like:
`
`The Java Revolution 1 5
`
`class convertible extends car { ...
`
`we're saying that the new convertible class will inherit all the functionality of the
`existing car class. convertible becomes a subclass of car, and conversely, car is
`convertible's superclass.
`
`Encapsulation is an equally simple idea. All it means is that every element of a
`program (methods, variables, etc.) must exist within a class, and only those ele(cid:173)
`ments that an object needs to see should be visible to that object. Thus, a class
`must explicitly specify whether a method or variable is "visible" to other classes.
`For instance, consider the code in Listing 1.6.
`
`Listing 1 . 6 Encapsulating Vehicle ID Number
`class car {
`protected int VehicleiD;
`public Scratch scratches[];
`}
`class AutoFactory {
`public void makeACar() {
`car TheAudi = new car();
`}
`
`In this example, an object of class AutoFactory can change TheAudi's array of
`scratches, but it can't change the VehideiD. This is encapsulation.
`
`Where C programs are divided into modules, a Java program is divided into
`classes. Classes are simply a way of dividing the functionality of the program
`into discrete chunks. The theory of classes is that they "model" the items in
`the real world that they're supposed to describe. Thus, a program that showed
`a car moving across the screen would probably have a class named Car that
`had variables like speed, color, and bumper stickers. Every method (func(cid:173)
`tion) and variable in a Java program exists within a class. For example, in
`our hello.java program (shown previously in Listing 1.3), we had to create a
`class that contained the main method instead of simply defining a main
`function as in hello.c.
`
`Starbucks Corp. Exhibit 1021
`
`
`
`16 Chapter 1
`
`A running Java program is made up entirely of objects. An object is simply an
`instance of a class. Take our car example. We can describe a car with the class
`shown in Listing 1. 7.
`
`Listing 1 . 7 Creating an Object Class
`class car {
`int speed:
`Color color:
`String bumper_stickers[J:
`public car() {
`color~ new Color(Color.blackl :
`speed ~ 100:
`bumper_sticker ~new String("Code happens"):
`
`public speed_up()
`speed++:
`}
`
`All this means, however, is that we know how to create a car-not that we've
`actually created one. In order to create one, we'd need to call new, as shown in
`Listing 1.8.
`
`Listing 1 . 8 Creating an Instance of a Class
`public void MakeACar() {
`car TheAudi ~new Car():
`while( !speedTrap ) {
`TheAudi .speed_up();
`}
`
`When you create an instance of a class, it is known as instantiating the class.
`When you instantiate the class, you get back an object. In our example, car is a
`class, while TheAudi is an object.
`
`Interfaces, described in more detail shortly, are an object-oriented feature that
`Java does not inherit from C++. In simple terms, an interface is a description of
`a class. For instance, our car example would translate to an interface, as shown
`in the following code snippet:
`
`interface car {
`public speed_up();
`
`Starbucks Corp. Exhibit 1021
`
`
`
`The Java Revolution 1 7
`
`But an interface is only a description. You can't instantiate an interface. In order
`to get a car object, you have to instantiate a class that implements the car inter(cid:173)
`face, as in Listing 1.9.
`
`Instantiating a Class with an Interface
`Listing 1 . 9
`class convertible implements car [
`int speed;
`Color color;
`Scratch scratches[];
`public convertible()
`}
`public speed_up()
`speed +~ 10;
`}
`
`Now we have a class that can be instantiated via new.
`
`Cooperating Objects
`The old computing world is made up of millions of islands of computing power,
`where huge, traditional applications toil away in splendid isolation from one
`another. Through various torturous mechanisms, these applications can some(cid:173)
`times exchange data, but for the most part they treat each other like obnoxious
`relatives-with tolerance, but not much respect.
`
`The new computing world, according to