You are on page 1of 13

A BRIEF HISTORY OF JAVA PLATFORM An edition of the Java platform is the name for a bundle of related programs from

Sun that allow for developing and running programs written in the Java programming language. The platform is not specific to any one processor or operating system, but rather an execution engine (called a virtual machine) and a compiler with a set of libraries that are implemented for various hardware and operating systems so that Java programs can run identically on all of them. Java Card: A technology that allows small

Runtime Environment (JRE), complementing the JVM with a just-in-time (JIT) compiler, converts intermediate bytecode into native machine code on the fly. Also supplied are extensive libraries, precompiled in which are several other components, some available only in certain editions. The essential components in the platform are the Java language compiler, the libraries, and the runtime environment in which Java intermediate bytecode "executes" according to the rules laid out in the virtual machine specification. OBJECT ORIENTED PROGRAMMING IN JAVA If you've never used an object-oriented programming language before, you'll need to learn a few basic concepts before you can begin writing any code. This lesson will introduce you to objects, classes, inheritance, interfaces, and packages. Each discussion focuses on how these concepts relate to the real world, while simultaneously providing an introduction to the syntax of the Java programming language. What Is an Object? An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life. This lesson explains how state and behavior are represented within an object, introduces the concept of data encapsulation, and explains the benefits of designing your software in this manner. What Is a Class? A class is a blueprint or prototype from which objects are created. This section defines a class that models the state and behavior of a real-world object. It intentionally focuses on the basics, showing how even a simple class can cleanly model state and behavior. What Is Inheritance? Inheritance provides a powerful and natural mechanism for organizing and structuring your software. This section explains how classes inherit state and behavior from their superclasses, and explains how to derive one class from another using the simple syntax provided by the Java programming language.

Java-based applications (applets) to be run securely on smart cards and similar smallmemory-footprint devices. Java ME (Micro Edition): Specifies several

different sets of libraries (known as profiles) for devices that are sufficiently limited that supplying the full set of Java libraries would take up unacceptably large amounts of storage. Java SE (Standard Edition): For general-

purpose use on desktop PCs, servers and similar devices. Java EE (Enterprise Edition): Java SE plus

various APIs useful for multi-tier client server enterprise applications. As of September 2009, the current version of the Java Platform is specified as either 1.6.0 or 6 (both refer to the same version). Version 6 is the product version, while 1.6.0 is the developer version. The Java Platform consists of several programs, each of which provides a distinct portion of its overall capabilities. For example, the Java compiler, which converts Java source code into Java bytecode (an intermediate language for the Java Virtual Machine (JVM)), is provided as part of the Java Development Kit (JDK). The Java

What Is an Interface? An interface is a contract between a class and the outside world. When a class implements an interface, it promises to provide the behavior published by that interface. This section defines a simple interface and explains the necessary changes for any class that implements it. What Is a Package? A package is a namespace for organizing classes and interfaces in a logical manner. Placing your code into packages makes large software projects easier to manage. This section explains why this is useful, and introduces you to the Application Programming Interface (API) provided by the Java platform. STANDARD SDK TOOLS Each of the development tools comes in a Microsoft Windows version (Windows) and a Solaris or Linux version. There is virtually no difference in features between versions. However, there are minor differences in configuration and usage to accommodate the special requirements of each operating system. (For example, the way you specify directory separators depends on the OS.) The following documents contain important information you will need to know to get the most out of the SDK tools. [Solaris] [Linux] [Windows] [Solaris and Linux] Setting the [Windows] Classpath [Solaris, Linux and How Classes are Windows] Found Tool Changes in Java [Solaris, Linux and Windows] 2 SDK, v1.4 SDK File Structure

Java Plug-inTM Tools

Basic Tools

These tools are the foundation of the Java 2 SDK. They are the tools you use to create and build applications. Tool Name Brief Description Links to Referenc javac The compiler for the [Solaris and Linux] Java programming language. java The launcher for Java [Solaris] [Linux] [W applications. In this release, a single launcher is used both for development and deployment. The old deployment launcher, jre, is no longer provided. javadoc API documentation [Solaris and Linux] generator. For links to Javadoc enhancements, Doclet API, Taglet API, doclets and more, see the Javadoc Tool Page appletviewer Run and debug applets [Solaris and Linux] without a web browser. jar Manage Java Archive [Solaris and Linux] (JAR) files. jdb The Java Debugger. [Solaris and Linux] javah C header and stub [Solaris and Linux] generator. Used to write native methods. javap Class file disassembler [Solaris and Linux] extcheck Utility to detect Jar [Solaris and Linux] conflicts. Remote Method Invocation (RMI) Tools These tools help to create apps that interact over the Web or other network. Links to Tool Name Brief Description Reference Pages rmic Generate stubs and [Solaris skeletons for remote and Linux] objects. [Windows] rmiregistry Remote object registry [Solaris service. and Linux] [Windows] rmid RMI activation system [Solaris daemon. and Linux] [Windows] serialver Return class [Solaris serialVersionUID. and Linux] [Windows]

The sections below provide a brief introduction to the tools in the Java 2 SDK, with links to their reference pages: Basic Tools (javac, java, javadoc, appletviewer, jar, jdb, javah, javap, extcheck) Remote Method Invocation (RMI) Tools (rmic, rmiregistry, rmid, serialver) Internationalization Tools (native2ascii) Security Tools (keytool, jarsigner, policytool, kinit, klist, ktab) Java IDL and RMI-IIOP Tools (tnameserv, idlj, orbd, servertool)

Internationalization Tool This tool helps to create localizable apps. Links to Tool Name Brief Description Reference Pages native2ascii Convert text to Unicode [Solaris Latin-1. and Linux] [Windows] Security Tools These security tools help you set security policies on your system and create apps that can work within the scope of security policies set at remote sites. Links to Tool Brief Description Reference Name Pages keytool Manage keystores and [Solaris certificates. and Linux] [Windows] jarsigner Generate and verify JAR [Solaris signatures. and Linux] [Windows] policytool GUI tool for managing policy [Solaris files. and Linux] [Windows] These security tools help you obtain, list, and manage Kerberos tickets. Links to Tool Brief Description Reference Name Pages kinit Tool for obtaining Kerberos v5 [Linux] tickets. Equivalent functionality [Windows] is available on the Solaris operating environment via the kinit tool. For example, for Solaris 8, see the kinit reference page. klist Command-line tool to list entries [Linux] in credential cache and key tab. [Windows] Equivalent functionality is available on the Solaris operating environment via the klist tool. For example, for Solaris 8, see the klist reference page. ktab Command-line tool to help the [Linux] user manage entires in the key [Windows] table. Equivalent functionality is available on the Solaris operating environment via the kadmin tool. For example, for Solaris 8, see the kadmin reference page.

Java IDL and RMI-IIOP Tools These tools are used when creating applications that use OMG-standard IDL and CORBA/IIOP. Tool Name with Brief Description Reference Links tnameserv Provides access to the naming service. idlj Generates .java files that map an OMG IDL interface and enable an application written in the Java programming language to use CORBA functionality. orbd Provides support for clients to transparently locate and invoke persistent objects on servers in the CORBA environment. ORBD is used instead of the Transient Naming Service, tnameserv. ORBD includes both a Transient Naming Service and a Persistent Naming Service. The orbdtool incorporates the functionality of a Server Manager, an Interoperable Naming Service, and a Bootstrap Name Server. When used in conjunction with the servertool, the Server Manager locates, registers, and activates a server when a client wants to access the server. servertool Provides ease-of-use interface for the application programmers to register, unregister, startup, and shutdown a server. Java Plug-in Tool Utilities for use in conjunction with the Java PluginTM product. Brief Description with Links to Tool Name Reference Pages unregbean Unregisters a packaged JavaBeans component over ActiveX. Unregbean is described on the Java Plug-in Scripting document on the web site.

Javadoc comments Javadoc is a documentation generator from Sun Microsystems for generating API documentation in HTML format from Java source code. The "doc comments" format used by Javadoc is the de facto industry standard for documenting Java classes. Some IDEs,[1] such

as Netbeansand Eclipse automatically generate Javadoc HTML. Many file editors assist the user in producing Javadoc source and use the Javadoc info as internal references for the programmer. Javadoc also provides an API for creating doclets and taglets, which allows you to analyze the structure of a Java application. This is how JDiffcan generate reports of what changed between two versions of an API. Contents [hide] 1 Structure of a Javadoc comment 2 Overview of Javadoc 3 Example 4 See also 5 Notes 6 External links

[edit]Overview of Javadoc The basic structure of writing document comments is embed them inside /** ... */. The Javadoc is written next to the items without any separating newline. The class declaration usually contains: /** * @author Firstname Lastname <address @ example.com> * @version 1.6 (The Java version used) * @since 2010.0331 (E.g. ISO 8601 YYYY.MMDD) */ public class Test { // class body } For methods there is (1) a short, concise, one line description to explain what the item does. This is followed by [2] a longer description that may span in multiple paragraphs. In those the details can be explained in full. This section, marked in brackets [], is optional. Last, there is (3) a tag section to list the accepted input arguments and return values of the method. /** * Short one line description. (1) * * Longer description. If there were any, it would be [2] * here. * * @param variable Description text text text. (3) * @return Description text text text. */ Variables are documented similarly to methods with the exception that part (3) is omitted. Here the variable contains only the short description: /** * Description of the variable here. */ private int debug = 0;

[edit]Structure of a Javadoc comment A Javadoc comment is set off from code by standard multi-line comment tags /* and */. The opening tag, however, has an extra asterisk, as in /**. 1. The first paragraph is a description

of the method documented. 2. Following the description are a

varying number of descriptive tags, signifying:

1. 2. 3. 4.

The parameters of the

method (@param) What the method returns

(@return) Any exceptions the method

may throw (@throws) Other less-common tags such

as @see (a "see also" tag)

Some of the available Javadoc tags[2] are listed in the table below: {@inheritDoc} Tag & Parameter Usage Applies Sinc to e

Copies the description from the overridden method.

Overridin 1.4.0 g Method

@author name

Describes an Class, author. Interface

{@link reference}

Class, Link to other Interface symbol. , Field, Method

@version version

Provides version Class, entry. Max Interface one per Class or Interface.

{@value}

Return the value of a static field.

Static Field

1.4.0

[edit]Example Describes since when this functionality has existed. Class, Interface , Field, Method An example of using Javadoc to document a method follows. Notice that spacing and number of characters in this example are as conventions state. Provides a Class, link to other Interface element of , Field, documentatio Method n. /** * Validates a chess move. * * Use {@link #doMove(int, int, int, int)} to move a piece. * * @param theFromFile file from which a piece is being moved * @param theFromRank rank from which a piece is being moved * @param theToFile file to which a piece is being moved * @param theToRank rank to which a piece is being moved * @return true if the move is valid, otherwise false */ boolean isValidMove(int theFromFile, int theFromRank, int theToFile, int theToRank) { ... } /** * Moves a chess piece. *

@since since-text

@see reference

@param name description

Describes a method parameter.

Method

@return description

Describes the Method return value.

Describes an @exception classna exception me description that may be Method @throws classname thrown from description this method.

Describes an @deprecated descri outdated Method ption method.

* @see java.math.RoundingMode */ boolean doMove(int theFromFile, int theFromRank, int theToFile, int theToRank) { ... } A Quick Introduction to Javadoc CISC 124, Fall 2001 1. What is Javadoc? 2. General format of Javadoc Comments 3. Tags 3.1. Tags for Classes 3.2 Tags for Methods 3.3 Tags for Variables 4. Running Javadoc 4.1. In the Labs 4.2. At home 4.3. Warning: Javadoc and BlueJ 4.4. Sending output to another folder 5. Javadoc and HTML 6. More Information

comments that appear at the top of each file and before the declaration of each class, method and top-level variable. There are two reasons for this requirement: 1. the format forces you to be precise and complete 2. it starts you in the habit of using Javadoc format, which is a widely-accepted industry standard You should have a Javadoc comment immediately before each class, method and top-level variable (that means a global or instance variable, not a local variable within a method). Your Javadoc comment at the beginning of the "main" class file should describe the entire program. 2. General format of Javadoc Comments All Javadoc comments have the following format: /** * Summary sentence. * More general information about the * program, class, method or variable which * follows the comment, using as many lines * as necessary. * * zero or more tags to specify more specific kinds * of information, such as parameters and return * values for a method */ You start out with the normal beginning of comment delimiter (/*) followed by another (*). All following lines start with an asterisk lined up under the first asterisk in the first line. The last line contains just the normal end of comment delimiter (*/). The first sentence is a "summary sentence". This should be a short description of the program, class, method or variable that can stand on its own. Even though it's refered to as a "summary sentence", it is often a phrase rather than a complete sentence, as in the example below. It can extend over several lines if needed; just don't include any blank lines. (It ends with the first period, so you must avoid using abbreviations such as "e.g." in this sentence!) Following the summary sentence, you may include more sentences to give more details; again, don't include any blank lines. Following this general description, there should be a blank line, then a sequence of "tags". Different tags will be appropriate for different situations. Here is an example of a Javadoc comment without tags which describes the variable declarated immediately below it:

1. What is Javadoc? Traditionally, when you write a program you must write a separate document recording how the program works. When the program changes, the separate documentation must change as well. For large programs that are constantly being changed and improved, it is a tedious and error-prone task to keep the documentation consistent with the actual code. Javadoc is a tool that helps with this problem. Instead of writing and maintaining separate documentation, the programmer writes speciallyformatted comments in the Java code itself. Javadoc takes these comments and transforms them into documentation in HTML (web page) format. For a short example of documentation generated by Javadoc, see the external documentation for our sample program. Another good example of a program with Javadoc comments is the SavitchIn class, which is printed in an appendix to the text and also included in the CD which accompanies the text. Here is the output you get when you run Javadoc on SavitchIn. For a larger, real-life example of documentation generated by Javadoc, see the Java 1.3 API documentation. In CISC 124, you are required to use Javadoc format for "header" comments -- that is, the block

/** * The number of students in the class. This variable must not be * negative or greater than 200. */ public int numStudents;

Note: You still can and should have comments within methods, describing local variables and the computing going on inside the methods. There is, however, no Javadoc format for these comments. Use // or /*..*/, whichever you prefer. 3. Tags The general form of a tag is: * @name comment where the name of the tag specifies what kind of information we're giving and the comment gives the information. For example, the author tag is used to tell us who wrote a class or program, as in * @author William Shakespeare Each tag should start on a new line. The tag comments can extend into multiple lines if necessary, but there should be no blank lines in between tags. 3.1. Tags for Classes In a Javadoc comment before a class definition, you should have an author tag, specifying who wrote the program. @author your full name, as it will appear in a class list (no nicknames, please), plus your lab section For example: @author Jane Smith, lab X If you worked with a partner, make an author tag for each one of you, on separate lines.

If your method throws an exception, you should also include an exception tag: @exception <name of exception> description of circumstances under which the exception is thrown For example: * @exception NumberFormatException raised if the user's input is not in valid integer format If your method throws more than one exception, they should appear in alphabetical order by exception name. Exception tags should follow param and return tags. 3.3 Tags for Variables A Javadoc comment before a variable declaration needs no tags. See Section 2 for an example. 4. Running Javadoc Javadoc is a DOS program without a fancy user interface. The use of a batch file, however, makes it quite simple to run. 4.1. In the Labs Download the file jdrun.bat into the folder containing your program. Find the file using My Computer or Windows NT Explorer and double-click it. It will create Javadoc output in that folder. 4.2. At home To run Javadoc on your home computer, download the file JDathome.bat into the folder containing your program. Use Notepad to edit this file and changec:\javafolder to the full name of your SDK installation folder. If you have downloaded BlueJ at home, you will know where that folder is. If you are using JBuilder (version 3 or later) at home, use the name of the folder in which you installed JBuilder plus \bin. So, for example, if you've installed JBuilder intoc:\JBuilder5, your SDK folder is c:\JBuilder5\bin. Once you've made that change to the batch file, you can double-click on it to run it, just like in the labs. 4.3 Warning: Javadoc and BlueJ Some of you may discover that you can run Javadoc directly from BlueJ. This would be a great convenience, but unfortunately BlueJ doesn't use the Javadoc flags I want you to use. Specifically, if you run BlueJ that way, your output will only contain information about public methods and variables. That's what you want for most production programs, for generating user information, but it's not what we want for CISC 124; you need documentation for all of your code. So you should use run Javadoc separately using one of the above batch files.

3.2 Tags for Methods For each parameter to a method, include a param tag: @param <name of parameter> short description of parameter For example, * @param size number of elements in the array If a method has several parameters, the param tags should appear in the same order as the parameters are declared. A method with no parameters will have noparam tags. After the param tag(s), if any, include a return tag unless your return type is void (no return value): @return short description of return value For example: * @return true if the value was found in the array

4.4. Sending output to another folder When you run the batch files I've given, all of the Javadoc output (lots of files) is put in the folder containing your program. Sometimes it's convenient to send the Javadoc output somewhere else. To do this, add the switch -d <folder> to the batch files, where <folder> is the name of the folder where you want the output to go. It can be a full path name, or relative to the folder with the programs, so -d doc will send the output to a sub-folder of the folder with the programs called doc. 5. Javadoc and HTML You will notice that Javadoc does not retain the line breaks or extra spaces in your comments. This is because Javadoc outputs HTML (HyperText MarkupLanguage, the language in which web pages are written). HTML formats paragraphs according to the width of the screen, ignoring line breaks and extra spaces in the source. If you want some control over the formatting of your comments in the generated web pages, you can imbed HTML commands in your comments. If you don't know HTML, here are 3 HTML commands that can be useful: <br> Forces a line break, so the next word appears at the beginning of a new line <p> Same as <br>, but skips a line first <pre> Marks the start of a "pre-formatted" section. Everything between this command and the next </pre> command is reproduced in a fixed-point font, with spaces and line breaks preserved. </pre> Marks the end of a "pre-formatted" section.

about Javadoc for CISC 124. There are, however, more tags and more things you can do with Javadoc. For more complete information on Javadoc comments, plus lots of stylistic advice, see How to Write Doc Comments for Javadoc You can also see the Javadoc Home Page for more information on how to run and customize Javadoc. The Javadoc 1.2 Reference Page provides a good, concise description of both the comment format and how to run Javadoc, including the commandline options. Additions to the JAVA 2 PLATFORM Java SE 7 Java 7 (codename Dolphin[48]) is an upcoming major update to Java, expected to release on July 28th, 2011.[49] The development period is organized into thirteen milestones; on February 18, 2011, milestone 13, the last milestone was reached.[50][51] Multiple builds, which generally include enhancements and bug fixes, are released per milestone. The Feature list at the Open JDK 7 project lists many of the expected feature changes. The expected feature additions for Java 7[52] JVM support for dynamic languages,

following the prototyping work currently done on the Multi Language Virtual Machine Compressed 64-bit pointers[53] Available in Language changes under Project Coin.[54] The features accepted for inclusion in

Java 6 with -XX:+UseCompressedOops


[55]

The example program and its Javadoc output contain examples of each of these commands. They should be enough to produce any spacing or indentation you feel is necessary. Dividing long comments into paragraphs with <p> is all that's really necessary to make your output clear. If you already know HTML, you'll know how to produce some other effects, such as boldface type or bulleted lists. You can do this if you like, but don't waste too much time on it. You will not get extra marks for fancy Javadoc output. The emphasis here is on clear, accurate content. 6. More Information This web page tells you all you really need to know

Project Coin are: Strings in switch[56] Automatic resource management[57] Improved Type Inference for Generic

Instance Creation[58] Simplified Varargs Method Invocation[59] Better integral literals allowing for

underscores as digit separators

Concurrency utilities under JSR

expressions would be included in Java 8 and asked for community input to refine the feature.[70] Parts of project Coin that are not

166[60] New file I/O library to enhance

platform independence and add support for metadata and symbolic links. The new packages are java.nio.file and java.nio.file.attribute[61][62] Library-level support for Elliptic

included in Java 7

curve cryptography algorithms An XRender pipeline for Java 2D,

CLASSES AND OBJECTS CLASSES AND OOPS PROGRAMMING What Is an Object? Objects are key to understanding objectoriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle. Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming. Take a minute right now to observe the real-world objects that are in your immediate area. For each object that you see, ask yourself two questions: "What possible states can this object be in?" and "What possible behavior can this object perform?". Make sure to write down your observations. As you do, you'll notice that real-world objects vary in complexity; your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn off), but your desktop radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming.

which improves handling of features specific to modern GPUs New platform APIs for the graphics

features originally planned for release in Java version 6u10 Enhanced library-level support for

new network protocols, including SCTP and Sockets Direct Protocol Upstream updates to XML and

Unicode Lambda, Jigsaw, and part of Coin were dropped from Java 7, which will be released in mid 2011. Java 8 will be implemented with the remaining features in late 2012.[63] [edit]Java SE 8 Java 8 is expected in late 2012
[64]

and will

include at a minimum the features that were planned for Java 7 but later deferred. Modularization of the JDK under

Project Jigsaw[65][66] Language-level support for lambda

expressions (officially, lambda expressions; unofficially, closures) under Project Lambda.[67] There was an ongoing debate in the Java community on whether to add support for lambda expressions.[68]
[69]

Sun later declared that lambda

Bundling code into individual software objects provides a number of benefits, including: 1. Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system. 2. Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world. 3. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, taskspecific objects, which you can then trust to run in your own code. 4. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine. What Is a Class? In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objectsknown as bicycles. A class is the blueprint from which individual objects are created. The following Bicycle class is one possible implementation of a bicycle:

A software object. Software objects are conceptually similar to realworld objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation a fundamental principle of objectoriented programming. Consider a bicycle, for example:

class Bicycle { int cadence = 0; int speed = 0; int gear = 1; void changeCadence(int newValue) { cadence = newValue; } void changeGear(int newValue) { gear = newValue; } void speedUp(int increment) {

A bicycle modeled as a software object. By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6.

speed = speed + increment;

cadence:50 speed:10 gear:2 cadence:40 speed:20 gear:3 What Is Inheritance? Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio. Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:

void applyBrakes(int decrement) { speed = speed - decrement; } void printStates() { System.out.println("cadence:"+cadence+" speed:"+speed+" gear:"+gear); } } The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion of bicycle objects. The fields cadence, speed, and gear represent the object's state, and the methods (changeCadence, changeGear, speedUp etc.) define its interaction with the outside world. You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete application; it's just the blueprint for bicycles that might be used in an application. The responsibility of creating and using new Bicycle objects belongs to some other class in your application. Here's a BicycleDemo class that creates two separate Bicycle objects and invokes their methods:

class BicycleDemo { public static void main(String[] args) { // Create two different Bicycle objects Bicycle bike1 = new Bicycle(); Bicycle bike2 = new Bicycle(); // Invoke methods on those objects bike1.changeCadence(50); bike1.speedUp(10); bike1.changeGear(2); bike1.printStates(); bike2.changeCadence(50); bike2.speedUp(10); bike2.changeGear(2); bike2.changeCadence(40); bike2.speedUp(10); bike2.changeGear(3); bike2.printStates(); } }

A hierarchy of bicycle classes. The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from: class MountainBike extends Bicycle {

The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles:

// new fields and methods defining a mountain bike would go here } This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass. What Is an Interface? As you've already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off. In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows: interface Bicycle { void changeCadence(int newValue); revolutions per minute void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); } To implement this interface, the name of your class would change (to a particular brand of bicycle, for example, such asACMEBicycle), and you'd use the implements keyword in the class declaration: class ACMEBicycle implements Bicycle { // remainder of this class implemented as before } Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in // wheel

its source code before the class will successfully compile.

What Is a Package? A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages. The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. This library is known as the "Application Programming Interface", or "API" for short. Its packages represent the tasks most commonly associated with general-purpose programming. For example, a String object contains state and behavior for character strings; a File object allows a programmer to easily create, delete, inspect, compare, or modify a file on the filesystem; a Socket object allows for the creation and use of network sockets; various GUI objects control buttons and checkboxes and anything else related to graphical user interfaces. There are literally thousands of classes to choose from. This allows you, the programmer, to focus on the design of your particular application, rather than the infrastructure required to make it work. The Java Platform API Specification contains the complete listing for all packages, interfaces, classes, fields, and methods supplied by the Java Platform 6, Standard Edition. Load the page in your browser and bookmark it. As a programmer, it will become your single most important piece of reference documentation.

You might also like