Writing Java Programs

You're probably already familiar with Java, if only because of Java applets. Applets—windowed Java applications designed to work in browsers—took the world by storm when first introduced, and all major browsers support some version of Java these days. You can find millions of applets on the Internet, and you can pick up whole banks of them for free. There are even applets out there that work with XML.

A Java applet takes up a predefined area in a browser and can display graphics, controls (such as buttons and text fields), text, and more. It's interactive because it runs in your browser. As mentioned, applets took the Internet by storm when first introduced. However, they're on the wane now, largely because of other solutions that can be easier to program, such as Dynamic HTML, or more powerful, such as Shockwave.

Don't worry about Java though—as applets have become less popular (although still very popular), Java applications have gathered strength. The main reason that Java applications have become so powerful is that they're nearly as powerful as C++, but they're also cross-platform—you can use the same application in Windows or UNIX, for example. Many large corporations have switched from using C++ internally to using Java for most programming.

A Java application does not run in a browser like an applet—it's a free-standing program. Java applications can themselves create windows, such as applets, and we'll see how to do that here. In fact, Java applications can act as browsers, and we'll see an example of that in the next chapter with a Java application that reads an XML document from the Internet and uses it to display graphics. In that case, the XML document will specify circles to draw, and we'll be creating a graphical, not text-based, browser, which is typical of the kinds of things you can do when you create your own XML applications.

Our XML Java work will center on writing Java applications, not applets. (For security reasons, applets are very restricted in terms of what they can do, and they can't handle most types of file access—we don't want to restrict our XML programs to work only in browsers.) So how do you create a Java application? You write applications as Java code and then compile them with the Java Software Development Kit (SDK). (Before Java 2, the SDK was called the Java Development Kit [JDK], and some people, including some Web pages at Sun, still call it that.) The compiled application is ready to run, and we'll see how to do that here.

I'll make this more concrete with an immediate example. Here's how to create an application named app, which I'll store in a file named app.java (I'll go through the details of this application in this chapter):

public class app
{
    public static void main(String[] args)
    {
        System.out.println("Welcome to Java");
    }
}

I can use the Java compiler, which is named javac, to compile this file into a bytecode file named app.class, and app.class is what you actually run. The bytecodes in app.class are what Java reads and executes. (Java bytecodes are very compact compared to text, which makes applets fast to download. You can run the same bytecode file on many different operating systems, which makes it cross-platform.) Here's how you use javac to compile app.java (I'm using % as a generic command-line prompt, following the UNIX usage, where the prompt often is %; on an operating platform such as Windows, this prompt will be something like C:XML>):

%javac app.java

This creates app.class, and it's that file you use when running that application. To run the application, you use the tool named java (which comes with the Java SDK), like this:

%javac app.java
%java app
Welcome to Java

As you can see, the java tool executes the bytecode file app.class, and the result—the text Welcome to Java—appears. As mentioned, I'm using % as a generic command-line prompt because Java is available on many platforms. In Windows, you use these tools in an MS DOS window like this:

C:>java app
Welcome to Java

That's what running a Java application looks like. As we'll see, there are many similarities between Java and JavaScript—but there are also significant differences. For example, we'll need to indicate the type of variables in Java, which you don't have to do in JavaScript, and Java is also a lot more object-oriented than JavaScript.

Java Is Object-Oriented from the Ground Up

We first got a look at object-oriented programming when working with JavaScript, but that was only a quick glance. Object-oriented programming is integral to every aspect of Java. For example, take a look at the application we just saw:

public class app
{
    public static void main(String[] args)
    {
        System.out.println("Welcome to Java");
    }
}

The very first line—public class app—defines a class named app. Our whole program is based on that class because, unlike JavaScript, every line of code that you write in Java must be part of a class (or an interface, which is a more generalized form of class). When Java runs this application, it creates an object of this class and gives that object control. So, although you can optionally use objects in JavaScript, there's no avoiding them in Java.

I'll take a closer look at the idea behind classes now because we'll have to understand more about them than we did when discussing JavaScript. Object-oriented programming is really just another technique to let you implement that famous programming dictum: Divide and conquer.

Here's the idea: You encapsulate data and functions into objects, which makes objects into self-contained units. The data inside an object can be purely internal to the object, in which case it's called private data, or it can be accessible externally, in which case it's called public data.

The functions built into an object can also be purely private, or they can be public. In fact, ideally, the object should interact with the rest of the program only through a well-defined interface as created by its public functions. As we saw in Chapter 6, "Understanding JavaScript," functions that are part of classes or objects are called methods.

Object-oriented programming was first developed to let programmers handle larger programs by breaking them up into functional units that can be easily conceptualized. As you know, you can already break your code up into functions; object-oriented programming goes a step further than that, letting you create objects that can contain not just one function, but many, as well as internal data items. When you encapsulate part of your code into an object, it lets you think of that part of the program in an easily conceptualized way, and that's the motivation behind object-oriented programming.

For example, consider a car—but consider it not as a sleek new automobile, but as an assemblage of pipes, wires, valves, switches, gasoline, and all the various parts that make it work. Now imagine that you are responsible yourself for handling everything that the car usually does itself, such as pumping the fuel, igniting the fuel, transmitting power to the wheels, regulating electrical power, and more. A device requiring such attention would be impossible to drive. Now imagine all those functions back where they should be, internal to the car, and interacting with each other automatically as needed when you step on the gas. You think of the result simply as a car—an easily imagined single concept. All you have to do is to turn it on and step on the gas.

That's the idea behind encapsulation—you can take a complex system that requires a lot of attention and turn it into an object that handles the details internally when you pass control to it. If the first dictum of object-oriented programming is, "Divide and conquer," then the second is surely "Out of sight, out of mind."

In Java, object-oriented programming revolves around a few key concepts: classes, data members, inheritance, methods, and objects. This list summarizes these terms:

  • Class. A class can be thought of as a template from which you can create objects. The definition of the class includes the formal specifications for the class and any data and methods in it.

  • Data members. The data members of a class are the variables that are part of an object. You store the data that the object uses in its data members.

  • Inheritance. This is the process of deriving one class, called the derived class, from another, the base class, and being able to make use of the base class's methods in the derived class, while adding new functionality to the derived class.

  • Method. A method is a function built into an object. Methods can be part of classes (class methods) or objects (object methods), as we'll see in this chapter.

  • Object. This is an instance of a class—what you create with classes. You can think of a class as the type of an object. When you've created an object, you can customize it by storing data in it (which you can't do with a class).

All these constructs are important to object-oriented programming, and we'll get more details on each of them in this chapter as we see how to create our own classes.

Getting the Java SDK

To create your own Java applications, you'll need to get and install the Java SDK, at http://java.sun.com/js2e. After downloading the Java SDK, usually as one executable package that installs itself, follow the installation instructions on the http://java.sun.com site.

At this point, I'd love to be able to give detailed instructions on how to install the Java SDK, but that's a trap too many books have fallen into. The actual installation procedure has changed so often and so many times that any book that covers Java (and I've written many on Java) and tries to give those instructions is sure to make itself obsolete immediately. On the other hand, in recent versions, all you have to do is run an executable program that you download, and it'll do all the work for you.

As indicated in the Sun installation instructions, you must make sure that your machine can find the Java tools, including the Java compiler, javac. To do this, make sure that the Java bin subdirectory is in your computer's path. For example, in Windows, the bin subdirectory is c:jdk1.2.2in for the Java 2 SDK by default, version 1.2.2. You add a line like the following to autoexec.bat:

SET PATH=%PATH%;C:JDK1.2.2BIN

Depending on your operating system, you must reboot your computer to make these changes take effect. Now that the bin directory is in the path, you'll be able to use the Java tools from the command line; otherwise, you'll have to preface them with a pathname each time you want to use them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.124.21