Java Help, Java Tutorials, Java Programming, Java Tricks
Lesson Two
Thinking in Objects: An Analogy
CONTENTS
Objects and Classes
Behavior and Attributes
Attributes
Behavior
Creating a Class
Inheritance, Interfaces, and Packages
Inheritance
Creating a Class Hierarchy
How Inheritance Works
Single and Multiple Inheritance
Interfaces and Packages
Creating a Subclass
Summary
Q&A
Object-oriented programming (OOP) is one of the biggest programming ideas of
recent years, and you might worry that you must spend ears learning all about
object-oriented programming methodologies and how they can make your life easier
than The Old Way of programming. It all comes down to organizing your programs
in ways that echo how things are put together in the real world.
Today you’ll get an overview of object-oriented programming concepts in Java and
how they relate to how you structure your own
programs:
What classes and objects are and how they relate to each other
The two main parts of a class or object: its behaviors and its attributes
Class inheritance and how inheritance affects the way you design your programs
Some information about packages and interfaces
If you’re already familiar with object-oriented programming, much of today’s
lesson will be old hat to you.
You may want to skim it and go to a movie today instead. Tomorrow, you’ll get
into more specific details.
Thinking in Objects: An Analogy
Consider, if you will, Legos. Legos, for those who do not spend much time with
children, are small plastic building blocks in various colors and sizes. They
have small round bits on one side that fit into small round holes on other Legos
so that they fit together snugly to create larger shapes. With different Lego
parts (Lego wheels, Lego engines, Lego hinges, Lego pulleys), you can put
together castles, automobiles, giant robots that swallow cities, or just about
anything else you can imagine. Each Lego part is a small object that fits
together with other small objects in predefined ways to create other larger
objects. That is roughly how object-oriented
programming works: putting together smaller elements to build larger ones.
Here’s another example. You can walk into a computer store and, with a little
background and often some help, assemble an entire pc computer system from
various components: a motherboard, a CPU chip, a video card, a hard disk, a
keyboard, and so on. Ideally, when you finish assembling all the various
self-contained units, you have a system in which all the units work together to
create a larger system with which you can solve the problems you bought the
computer for in the first place.
Internally, each of those components may be vastly complicated and engineered by
different companies with different methods of design. But you don’t need to know
how the component works, what every chip on the board does, or how, when you
press the A key, an A gets sent to your computer. As the assembler of the
overall system, each component you use is a self-contained unit, and all you are
interested in is how the units interact with each other. Will this video card
fit into the slots on the motherboard, and will this monitor work with this
video card? Will each particular component speak the right commands to the other
components it interacts with so that each part of the computer is understood by
every other part? Once you know what the interactions are between the components
and can match the interactions, putting together the overall system is easy.
What does this have to do with programming? Everything. Object-oriented
programming works in exactly this same way. Using object-oriented programming,
your overall program is made up of lots of different self-contained components
(objects), each of which has a specific role in the program and all of which can
talk to each other in predefined ways.
Objects and Classes
Object-oriented programming is modeled on how, in the real world, objects are
often ade up of many kindsof smaller objects. This capability of combining
objects, owever, is only one very general aspect ofobject-oriented programming.
Object-oriented rogramming provides several other concepts and features to make
creating and using objects easier and more flexible, and the most important of
these features is classes.
When you write a program in an object-oriented language, you don’t define actual
objects. You define classes of objects, where a class is a template for multiple
objects with similar features. Classes embody all the features of a particular
set of objects. For example, you might have a Tree class that describes the
features of all trees (has leaves and roots, grows, creates chlorophyll). The
Tree class serves as an abstract model for the concept of a tree-to reach out
and grab, or interact with, or cut down a tree you have to have a concrete
instance of that tree. Of course, once you have a tree class, you can create
lots of different instances of that tree, and each different tree instance can
have different features (short, tall, bushy, drops leaves in autumn), while
still behaving like and being immediately recognizable as a tree (see Figure
2.1).
Figure 2.1 : The Tree class and several Tree instances.
New Term
A class is a generic template for a set of objects with similar features.
An instance of a class is another word for an actual object. If class is the
general (generic) representation of an object, an instance is its concrete
representation. So what, precisely, is the difference between an instance and an
object? Nothing, really. Object is the more general term, but both instances and
objects are the concrete representation of a class. In fact, the terms instance
and object are often used interchangeably in OOP lingo.
An instance of a tree and a tree object are both the same thing.
New Term
An instance is the specific concrete representation of a class.
Instances and objects are the same thing.
What about an example closer to the sort of things you might want to do in Java
programming? You might create a class for the user interface element called a
button. The Button class defines the features of a button (its label, its size,
its appearance) and how it behaves. (Does it need a single-click or a
double-click to activate it? Does it change color when it’s clicked? What does
it do when it’s activated?) After you define the Button class, you can then
easily create instances of that button-that is, button objects-that all take on
the basic features of the button as defined by the class, but may have different
appearances and behavior based on what you want that particular button to do. By
creating a Button class, you don’t have to keep rewriting the code for each
individual button you want to use in your program, and you can reuse the Button
class to create different kinds of buttons as you need them in this program and
in other programs.
Tip
If you’re used to programming in C, you can think of a class as sort of creating
a new composite data type by using struct and typedef. Classes, however, can
provide much more than just a collection of data, as you’ll discover in the rest
of today’s lesson. When you write a Java program, you design and construct a set
of classes. Then when your program runs, instances of those classes are created
and discarded as needed. Your task, as a Java programmer, is to create the right
set of classes to accomplish what your program needs to accomplish. Fortunately,
you don’t have to start from the very beginning: The Java environment comes with
a standard set
of classes (called a class library) that implement a lot of the basic behavior
you need-not only for basic programming tasks (classes to provide basic math
functions, arrays, strings, and so on), but also for graphics and networking
behavior. In many cases, the Java class libraries may be enough so that all you
have to do in your Java program is create a single class that uses the standard
class libraries. For complicated Java programs, you may have to create a whole
set of classes with defined interactions between them.
New Term
A class library is a collection of classes intended to be reused repeatedly in
different programs. The standard Java class libraries contain quite a few
classes for accomplishing basic programming tasks in Java.
Behavior and Attributes
Every class you write in Java has two basic features: attributes and behavior.
In this section you’ll learn about each one as it applies to a theoretical
simple class called Motorcycle. To finish up this section, you’ll create the
Java code to implement a representation of a motorcycle.
Attributes
Attributes are the individual things that differentiate one object from another
and determine the appearance, state, or other qualities of that object. Let’s
create a theoretical class called Motorcycle. A motorcycle class might include
the following attributes and have these typical values:
l Color: red, green, silver, brown
l Style: cruiser, sport bike, standard
l Make: Honda, BMW, Bultaco
Attributes of an object can also include information about its state; for
example, you could have features for engine condition (off or on) or current
gear selected.
Attributes are defined in classes by variables. Those variables’ types and names
are defined in the class, and each object can have its own values for those
variables. Because each instance of a class can have different values for its
variables, these variables are often called instance variables.
New Term
An instance variable defines the attributes of the object. Instance variables’
types and names are defined in the class, but their values
are set and changed in the object. Instance variables may be initially set when
an object is created and stay constant throughout the life of the object, or
they may be able to change at will as the program runs. Change the value of the
variable, and you
change an object’s attributes. In addition to instance variables, there are also
class variables, which apply to the class itself and to all its
instances. Unlike instance variables, whose values are stored in the instance,
class variables’ values are stored in the class itself. You’ll learn about class
variables later on this week and more specifics about instance variables
tomorrow.
Behavior
A class’s behavior determines how an instance of that class operates; for
example, how it will “react” if asked to do something by another class or object
or if its internal state changes. Behavior is the only way objects can do
anything to themselves or have anything done to them. For example, to go back to
the theoretical Motorcycle class, here are some behaviors that the Motorcycle
class might have:
l Start the engine
l Stop the engine
l Speed up
l Change gear
l Stall
To define an object’s behavior, you create methods, a set of Java statements
that accomplish some task. Methods look and behave just like functions in other
languages but are defined and accessible solely inside a class. Java does not
have functions defined outside classes (as C++ does).
New Term
Methods are functions defined inside classes that operate on instances
of those classes.
While methods can be used solely to operate on an individual object, methods are
also used between objects to communicate with each other. A class or an object
can call methods in another class or object to communicate changes in the
environment or to ask that object to change its state. Just as there are
instance and class variables, there are also instance and class methods.
Instance methods (which are so common that they’re usually just called methods)
apply and operate on an instance of a class; class methods apply and operate on
the class itself. You’ll learn more about class methods later on this week.
Creating a Class
Up to this point, today’s lesson has been pretty theoretical. In this section,
you’ll create a working example of the Motorcycle class so that you can see how
instance variables and methods are defined in a class in Java. You’ll also
create a Java application that creates a new instance of the Motorcycle class
and shows its instance variables.
Note
I’m not going to go into a lot of detail about the actual syntax of this example
here. Don’t worry too much about it if you’re not really sure
what’s going on; it will become clear to you later on this week. All you really
need to worry about in this example is understanding the
basic parts of this class definition. Ready? Let’s start with a basic class
definition. Open the text editor you’ve been using to create Java source code
and enter the following (remember, upper- and lowercase matters):
class Motorcycle {
}
Congratulations! You’ve now created a class. Of course, it doesn’t do very much
at the moment, but that’s a
Java class at its very simplest.
First, let’s create some instance variables for this class-three of them, to be
specific. Just below the first line,
add the following three lines:
String make;
String color;
boolean engineState = false;
Here you’ve created three instance variables: Two, make and color, can contain
String objects (a string is the generic term for a series of characters; String,
with a capital S, is part of that standard class library mentioned earlier). The
third, engineState, is a boolean variable that refers to whether the engine is
off or on; a value of false means that the engine is off, and true means that
the engine is on. Note that boolean is lowercase b.
New Term
A boolean is a value of either true or false.
Technical Note
boolean in Java is a real data type that can have the values true or false.
Unlike in C, booleans are not numbers. You’ll hear about this again tomorrow so
that you won’t forget. Now let’s add some behavior (methods) to the class. There
are all kinds of things a motorcycle can do, but to keep things short, let’s add
just one method-a method that starts the engine. Add the following lines below
the
instance variables in your class definition:
void startEngine() {
if (engineState == true)
System.out.println(“The engine is already on.”);
else {
engineState = true;
System.out.println(“The engine is now on.”);
}
}
The startEngine() method tests to see whether the engine is already running (in
the part engineState == true) and, if it is, merely prints a message to that
effect. If the engine isn’t already running, it changes the state of the engine
to true (turning the engine on) and then prints a message. Finally, because the
startEngine() method doesn’t return a value, its definition includes the word
void at the beginning. (You can also define methods to return values; you’ll
learn more about method definitions on Day 6, “Creating Classes and Applications
in Java.”)
Tip
Here and throughout this book, whenever I refer to the name of a method, I’ll
add empty parentheses to the end of the name (for
example, as I did in the first sentence of the previous paragraph: “The
startEngine() method…” This is a convention used in the
programming community at large to indicate that a particular name is a method
and not a variable. The parentheses are silent.
With your methods and variables in place, save the program to a file called
Motorcycle.java (remember that you should always name your Java source files the
same names as the class they define). Listing 2.1 shows what your program should
look like so far.
Listing 2.1. The Motorcycle.java file.
1:class Motorcycle {
2:
3: String make;
4: String color;
5: boolean engineState = false;
6:
7: void startEngine() {
8: if (engineState == true)
9: System.out.println(“The engine is already on.”);
10: else {
11: engineState = true;
12: System.out.println(“The engine is now on.”);
13: }
14: }
15:}
Tip
The indentation of each part of the class isn’t important to the Java compiler.
Using some form of indentation, however, makes your lass definition easier for
you and other people to read. The indentation used here, with instance variables
and methods indented from the lass definition, is the style used throughout this
book. The Java class libraries use a similar indentation. You can choose any
indentation style hat you like.
Before you compile this class, let’s add one more method just below the
startEngine() method (that is, between lines 14 and 15). The showAtts() method
is used to print the current values of all the instance variables in an instance
of your Motorcycle class. Here’s what it looks like:
void showAtts() {
System.out.println(“This motorcycle is a “
+ color + ” ” + make);
if (engineState == true)
System.out.println(“The engine is on.”);
else System.out.println(“The engine is off.”);
}
The showAtts() method prints two lines to the screen: the make and color of the
motorcycle object and whether the engine is on or off. Now you have a Java class
with three instance variables and two methods defined. Save that file again, and
compile it using one of the following methods:
Note
After this point, I’m going to assume you know how to compile and run Java
programs. I won’t repeat this information after this.
Windows
From inside a DOS shell, CD to the directory containing your Java source file,
and use the javac command to compile it:
javac Motorcycle.java
Macintosh
Drag and drop the Motorcycle.java file onto the Java Compiler icon.
Salaris
From a command line, CD to the directory containing your Java source file, and
use the javac command to compile it:
javac Motorcycle.java
When you run this little program using the java or Java Runner programs, you’ll
get an error. Why? When you run a compiled Java class directly, Java assumes
that the class is an application and looks for a main()
method. Because we haven’t defined a main() method inside the class, the Java
interpreter (java) gives you
an error something like one of these two errors:
In class Motorcycle: void main(String argv[]) is not defined
Exception in thread “main”: java.lang.UnknownError
To do something with the Motorcycle class-for example, to create instances of
that class and play with them-you’re going to need to create a separate Java
applet or application that uses this class or add a main()method to this one.
For simplicity’s sake, let’s do the latter. Listing 2.2 shows the main() method
you’ll add to the Motorcycle class. You’ll want to add this method to your
Motorcycle.java source file just before the last closing brace (}), underneath
the startEngine() and showAtts() methods.
Listing 2.2. The main() method for Motorcycle.java.
1: public static void main (String args[]) {
2: Motorcycle m = new Motorcycle();
3: m.make = “Yamaha RZ350″;
4: m.color = “yellow”;
5: System.out.println(“Calling showAtts…”);
6: m.showAtts();
7: System.out.println(“——–”);
8: System.out.println(“Starting engine…”);
9: m.startEngine();
10: System.out.println(“——–”);
11: System.out.println(“Calling showAtts…”);
12: m.showAtts();
13: System.out.println(“——–”);
14: System.out.println(“Starting engine…”);
15: m.startEngine();
16:}
With the main() method in place, the Motorcycle class is now an official
application, and you can
compile it again and this time it’ll run. Here’s how the output should look:
Calling showAtts…
This motorcycle is a yellow Yamaha RZ350
The engine is off.
——–
Starting engine…
The engine is now on.
——–
Calling showAtts…
This motorcycle is a yellow Yamaha RZ350
The engine is on.
——–
Starting engine…
The engine is already on.
Analysis
The contents of the main() method are all going to look very new to you, so
let’s go through it line by line so that you at least have a basic idea of what
it does (you’ll get details about the specifics of all of this tomorrow and the
day after).
The first line declares the main() method. The first line of the main() method
always looks like this; you’ll learn the specifics of each part later this week.
Line 2, Motorcycle m = new Motorcycle();, creates a new instance of the
Motorcycle class and stores a reference to it in the variable m. Remember, you
don’t usually operate directly on classes in your Java programs; instead, you
create objects from those classes and then call methods in those objects. Lines
3 and 4 set the instance variables for this Motorcycle object: The make is now a
Yamaha RZ350 (a very pretty motorcycle from the mid-1980s), and the color is
yellow.
Lines 5 and 6 call the showAtts() method, defined in your Motorcycle object.
(Actually, only 6 does; 5 just prints a message that you’re about to call this
method.) The new motorcycle object then prints out the values of its instance
variables-the make and color as you set in the previous lines-and shows that the
engine is off.
Line 7 prints a divider line to the screen; this is just for prettier output.
Line 9 calls the startEngine() method in the motorcycle object to start the
engine. The engine should now be on.
Line 11 prints the values of the instance variables again. This time, the report
should say the engine is now on.
Line 15 tries to start the engine again, just for fun. Because the engine is
already on, this should print the message The engine is already on.
Listing 2.3 shows the final Motorcycle class, in case you’ve been having trouble
compiling and running the one you’ve got (and remember, this example and all the
examples in this book are available on the CD that accompanies the book):
Listing 2.3. The final version of Motorcycle.java.
1: class Motorcycle {
2:
3: String make;
4: String color;
5: boolean engineState;
6:
7: void startEngine() {
8: if (engineState == true)
9: System.out.println(“The engine is already on.”);
10: else {
11: engineState = true;
12: System.out.println(“The engine is now on.”);
13: }
14: }
15:
16: void showAtts() {
17: System.out.println(“This motorcycle is a “
18: + color + ” ” + make);
19: if (engineState == true)
20: System.out.println(“The engine is on.”);
21: else System.out.println(“The engine is off.”);
22: }
23:
24: public static void main (String args[]) {
25: Motorcycle m = new Motorcycle();
26: m.make = “Yamaha RZ350″;
27: m.color = “yellow”;
28: System.out.println(“Calling showAtts…”);
29: m.showAtts();
30: System.out.println(“——”);
31: System.out.println(“Starting engine…”);
32: m.startEngine();
33: System.out.println(“——”);
34: System.out.println(“Calling showAtts…”);
35: m.showAtts();
36: System.out.println(“——”);
37: System.out.println(“Starting engine…”);
38: m.startEngine();
39: }
40:}
Inheritance, Interfaces, and Packages
Now that you have a basic grasp of classes, objects, methods, variables, and how
to put them all together in a Java program, it’s time to confuse you again.
Inheritance, interfaces, and packages are all mechanisms for organizing classes
and class behaviors. The Java class libraries use all these concepts, and the
best class libraries you write for your own programs will also use these
concepts.
Inheritance
Inheritance is one of the most crucial concepts in object-oriented programming,
and it has a very direct effect on how you design and write your Java classes.
Inheritance is a powerful mechanism that means when you write a class you only
have to specify how that class is different from some other class; inheritance
will give you automatic access to the information contained in that other class.
With inheritance, all classes-those you write, those from other class libraries
that you use, and those from the standard utility classes as well-are arranged
in a strict hierarchy (see Figure 2.2). Each class has a superclass (the class
above it in the hierarchy), and each class can have one or more subclasses
(classes below that class in the hierarchy). Classes further down in the
hierarchy are said to inherit from classes further up in the hierarchy.
Figure 2.2 : A class hierarchy.
Subclasses inherit all the methods and variables from their superclasses-that
is, in any particular class, if the superclass defines behavior that your class
needs, you don’t have to redefine it or copy that code from some other class.
Your class automatically gets that behavior from its superclass, that superclass
gets behavior from its superclass, and so on all the way up the hierarchy. Your
class becomes a combination of all the features of the classes above it in the
hierarchy.
New Term
Inheritance is a concept in object-oriented programming where all classes are
arranged in a strict hierarchy. Each class in the hierarchy
has superclasses (classes above it in the hierarchy) and any number of
subclasses (classes below it in the hierarchy). Subclasses inherit
attributes and behavior from their superclasses.
At the top of the Java class hierarchy is the class Object; all classes inherit
from this one superclass. Object is the most general class in the hierarchy; it
defines behavior inherited by all the classes in Java. Each class further down
in the hierarchy adds more information and becomes more tailored to a specific
purpose. In this way, you can think of a class hierarchy as defining very
abstract concepts at the top of the hierarchy and those ideas becoming more
concrete the farther down the chain of superclasses you go. Most of the time
when you write new Java classes, you’ll want to create a class that has all the
information some other class has, plus some extra information. For example, you
may want a version of a Button with its own built-in label. To get all the
Button information, all you have to do is define your class to inherit from
Button. Your class will automatically get all the behavior defined in Button
(and in Button’s superclasses), so all you have to worry about are the things
that make your class different from Button itself.
This mechanism for defining new classes as the differences between them and
their superclasses is called subclassing.
Subclassing involves creating a new class that inherits from some other class in
the class hierarchy. Using subclassing, you only need to define the differences
between your class and its parent; the additional behavior is all available to
your class through inheritance.
New Term
Subclassing is the process of creating a new class that inherits from some other
already-existing class.
What if your class defines an entirely new behavior and isn’t really a subclass
of another class? Your class can also inherit directly from Object, which still
allows it to fit neatly into the Java class hierarchy. In fact, if you create a
class definition that doesn’t indicate its superclass in the first line, Java
automatically assumes you’re inheriting from Object. The Motorcycle class you
created in the previous section inherited from
Object.
Creating a Class Hierarchy
If you’re creating a larger set of classes for a very complex program, it makes
sense for your classes not only to inherit from the existing class hierarchy,
but also to make up a hierarchy themselves. This may take some planning
beforehand when you’re trying to figure out how to organize your Java code, but
the advantages are significant once it’s done:
When you develop your classes in a hierarchy, you can factor out information
common to multiple classes in superclasses, and then reuse that superclass’s
information over and over again. Each subclass gets that common information from
its superclass.
l
Changing (or inserting) a class further up in the hierarchy automatically
changes the behavior of its subclasses-no need to change or recompile any of the
lower classes because they get the new information through inheritance and not
by copying any of the code.
l
For example, let’s go back to that Motorcycle class and pre tend you created a
Java program to implement all the features of a motorcycle. It’s done, it works,
and everything is fine. Now, your next task is to create a Java class called
Car.
Car and Motorcycle have many similar features-both are vehicles driven by
engines. Both have transmissions, headlamps, and speedometers. So your first
impulse may be to open your Motorcycle class file and copy over a lot of the
information you already defined into the new class Car.
A far better plan is to factor out the common information for Car and Motorcycle
into a more general class hierarchy. This may be a lot of work just for the
classes Motorcycle and Car, but once you add Bicycle, Scooter, Truck, and so on,
having common behavior in a reusable superclass significantly reduces the amount
of work you have to do overall.
Let’s design a class hierarchy that might serve this purpose. Starting at the
top is the class Object, which is the root of all Java classes. The most general
class to which a motorcycle and a car both belong might be called Vehicle. A
vehicle, generally, is defined as a thing that propels someone from one place to
another. In the Vehicle class, you define only the behavior that enables someone
to be propelled from point a to point b, and nothing more.
Below Vehicle? How about two classes: PersonPoweredVehicle and
EnginePoweredVehicle? EnginePoweredVehicle is different from Vehicle because it
has an engine, and the behaviors might include stopping and starting the engine,
having certain amounts of gasoline and oil, and perhaps the speed or gear in
which the engine is running. Person-powered vehicles have some kind of mechanism
for translating people motion into vehicle motion-pedals, for example. Figure
2.3 shows what you have so far.
Figure 2.3 : The basic vehicle hierarchy.
Now let’s become even more specific. With EnginePoweredVehicle, you might have
several classes:
Motorcycle, Car, Truck, and so on. Or you can factor out still more behavior and
have intermediate
classes for TwoWheeled and FourWheeled vehicles, with different behaviors for
each (see Figure 2.4).
Figure 2.4 : Two-wheeled and four-wheeled vehicles.
Finally, with a subclass for the two-wheeled engine-powered vehicles, you can
have a class for motorcycles. Alternatively, you could additionally define
scooters and mopeds, both of which are two-wheeled engine-powered vehicles but
have different qualities from motorcycles. Where do qualities such as make or
color come in? Wherever you want them to go-or, more usually, where they fit
most naturally in the class hierarchy. You can define the make and color on
Vehicle, and all the subclasses will have those variables as well. The point to
remember is that you have to define a feature or a behavior only once in the
hierarchy; it’s automatically reused by each subclass.
How Inheritance Works
How does inheritance work? How is it that instances of one class can
automatically get variables and methods from the classes further up in the
hierarchy?
For instance variables, when you create a new instance of a class, you get a
“slot” for each variable defined in the current class and for each variable
defined in all its superclasses. In this way, all the classes combine to form a
template for the current object, and then each object fills in the information
appropriate to its situation. Methods operate similarly: New objects have access
to all the method names of its class and its superclasses, but method
definitions are chosen dynamically when a method is called. That is, if you call
a method on a particular object, Java first checks the object’s class for the
definition of that method. If it’s not defined in the object’s class, it looks
in that class’s superclass, and so on up the chain until the method definition
is found (see Figure 2.5).
Figure 2.5 : How methods are located.
Things get complicated when a subclass defines a method that has the same
signature (name, number, and type of arguments) as a method defined in a
superclass. In this case, the method definition that is found first (starting at
the bottom and working upward toward the top of the hierarchy) is the one that
is actually executed. Therefore, you can intentionally define a method in a
subclass that has the same signature as a method in a superclass, which then
“hides” the superclass’s method. This is called overriding a method. You’ll
learn all about methods on Day 7, “More About Methods.”
New Term
Overriding a method is creating a method in a subclass that has the same
signature (name, number, and type of arguments) as a method in a superclass.
That new method then hides the superclass’s method
(see Figure 2.6).
Figure 2.6 : Overriding methods.
Single and Multiple Inheritance
Java’s form of inheritance, as you learned in the previous sections, is called
single inheritance. Single inheritance means that each Java class can have only
one superclass (although any given superclass can have multiple subclasses).
In other object-oriented programming languages, such as C++, classes can have
more than one superclass, and they inherit combined variables and methods from
all those classes. This is called multiple inheritance. Multiple inheritance can
provide enormous power in terms of being able to create classes that factor just
about all imaginable behavior, but it can also significantly complicate class
definitions and the code to produce them.
Java makes inheritance simpler by being only singly inherited.
Interfaces and Packages
There are two remaining concepts to discuss here: packages and interfaces. Both
are advanced topics for implementing and designing groups of classes and class
behavior. You’ll learn about both interfaces and packages on Day 16, “Packages
and Interfaces,” but they are worth at least introducing here.
Recall that each Java class has only a single superclass, and it inherits
variables and methods from that superclass and all its superclasses. Although
single inheritance makes the relationship between classes and the functionality
those classes implement easy to understand and to design, it can also be
somewhat restrictive-in particular, when you have similar behavior that needs to
be duplicated across different “branches” of the class hierarchy. Java solves
this problem of shared behavior by using the concept of interfaces, which
collect
method names into one place and then allow you to add those methods as a group
to the various classes that need them. Note that interfaces contain only method
names and interfaces (arguments, for example), not actual definitions.
Although a single Java class can have only one superclass (due to single
inheritance), that class can also implement any number of interfaces. By
implementing an interface, a class provides method implementations (definitions)
for the method names defined by the interface. If two very disparate classes
implement the same interface, they can both respond to the same method calls (as
defined by that interface), although what each class actually does in response
to those method calls may be very different.
New Term
An interface is a collection of method names, without definitions, that can be
added to classes to provide additional behavior not included
with those methods the class defined itself or inherited from its superclasses.
You don’t need to know very much about interfaces right now. You’ll learn more
as the book progresses, so if all this is very confusing, don’t panic! The final
new Java concept for today is packages. Packages in Java are a way of grouping
together related classes and interfaces in a single library or collection.
Packages enable modular groups of classes to be available only if they are
needed and eliminate potential conflicts between class names in different groups
of classes.
You’ll learn all about packages, including how to create and use them, in Week
3. For now, there are only a
few things you need to know:
l The class libraries in the Java Developer’s Kit are contained in a package
called java. The classes in the java package are guaranteed to be available in
any Java implementation and are the only classes guaranteed to be available
across different implementations. The java package itself contains other
packages for classes that define the language, the input and output classes,
some basic networking, the
window toolkit functions, and classes that define applets. Classes in other
packages (for example, classes in the sun or netscape packages) may be available
only in specific implementations.
By default, your Java classes have access to only the classes in java.lang (the
base language package inside the java package). To use classes from any other
package, you have to either refer to them explicitly by package name or import
them into your source file.
l
To refer to a class within a package, list all the packages that class is
contained in and the class name, all separated by periods (.). For example, take
the Color class, which is contained in the awt package (awt stands for Abstract
Windowing Toolkit). The awt package, in turn, is inside the java package. To
refer to the Color class in your program, you use the notation java.awt.Color.
l
Creating a Subclass
To finish up today, let’s create a class that is a subclass of another class and
override some methods. You’ll also get a basic feel for how packages work in
this example.
Probably the most typical instance of creating a subclass, at least when you
first start programming in Java, is creating an applet. All applets are
subclasses of the class Applet (which is part of the java.applet package). By
creating a subclass of Applet, you automatically get all the behavior from the
window toolkit and the layout classes that enable your applet to be drawn in the
right place on the page and to interact with system operations, such as
keypresses and mouse clicks. In this example, you’ll create an applet similar to
the Hello World applet from yesterday, but one that draws the Hello string in a
larger font and a different color. To start this example, let’s first construct
the class definition itself. Let’s go to your text editor, and enter the
following class definition:
public class HelloAgainApplet extends java.applet.Applet {
}
Here, you’re creating a class called HelloAgainApplet. Note the part that says
extends java.applet.Applet-that’s the part that says your applet class is a
subclass of the Applet class. Note that because the Applet class is contained in
the java.applet package, you don’t have automatic access to that class, and you
have to refer to it explicitly by package and class name.
The other part of this class definition is the public keyword. Public means that
your class is available to the Java system at large once it is loaded. Most of
the time you need to make a class public only if you want it to be visible to
all the other classes in your Java program, but applets, in particular, must be
declared to be public. (You’ll learn more about public classes in Week 3.)
A class definition with nothing in it doesn’t really have much of a point;
without adding or overriding any of its superclasses’ variables or methods,
there’s no reason to create a subclass at all. Let’s add some information to
this class, inside the two enclosing braces, to make it different from its
superclass.
First, add an instance variable to contain a Font object:
Font f = new Font(“TimesRoman”, Font.BOLD, 36);
The f instance variable now contains a new instance of the class Font, part of
the java.awt package. This particular Font object is a Times Roman font,
boldface, 36 points high. In the previous Hello World applet, the font used for
the text was the default font: 12-point Times Roman. Using a Font object, you
can change the font of the text you draw in your applet.
By creating an instance variable to hold this font object, you make it available
to all the methods in your class. Now let’s create a method that uses it.
When you write applets, there are several “standard” methods defined in the
applet superclasses that you will commonly override in your applet class. These
include methods to initialize the applet, to make it start running, to handle
operations such as mouse movements or mouse clicks, or to clean up when the
applet stops running. One of those standard methods is the paint() method, which
actually displays your applet onscreen. The default definition of paint()
doesn’t do anything-it’s an empty method. By overriding paint(), you tell the
applet just what to draw on the screen. Here’s a definition of paint():
public void paint(Graphics g) {
g.setFont(f);
g.setColor(Color.red);
g.drawString(“Hello again!”, 5, 40);
}
There are two things to know about the paint() method. First, note that this
method is declared public, just as the applet itself was. The paint() method is
actually public for a different reason-because the method it’s overriding is
also public. If a superclass’s method is defined as public, your override method
also has to be public, or you’ll get an error when you compile the class.
Second, note that the paint() method takes a single argument: an instance of the
Graphics class. The Graphics class provides platform-independent behavior for
rendering fonts, colors, and behavior for drawing basic lines and shapes. You’ll
learn a lot more about the Graphics class in Week 2, when you create more
extensive applets.
Inside your paint() method, you’ve done three things:
You’ve told the graphics object that the default drawing font will be the one
contained in the instance
variable f.
l
l You’ve told the graphics object that the default color is an instance of the
Color class for the color red. Finally, you’ve drawn your “Hello Again!” string
onto the screen, at the x and y positions of 5 and 25. The string will be
rendered in the new font and color.
l
For an applet this simple, this is all you need to do. Here’s what the applet
looks like so far:
public class HelloAgainApplet extends java.applet.Applet {
Font f = new Font(“TimesRoman”,Font.BOLD,36);
public void paint(Graphics g) {
g.setFont(f);
g.setColor(Color.red);
g.drawString(“Hello again!”, 5, 40);
}
}
If you’ve been paying close attention, you’ll notice that something is wrong
with this example up to this point. If you don’t know what it is, try saving
this file (remember, save it to the same name as the class:
HelloAgainApplet.java) and compiling it. You should get a bunch of errors
similar to this one:
HelloAgainApplet.java:7: Class Graphics not found in type declaration.
Why are you getting these errors? Because the classes you’re referring to in
this class, such as Graphics and Font, are part of a package that isn’t
available by default. Remember that the only package you have access to
automatically in your Java programs is java.lang. You referred to the Applet
class in the first line of the class definition by referring to its full package
name (java.applet.Applet). Further on in the program,
however, you referred to all kinds of other classes as if they were available.
The compiler catches this and tells you that you don’t have access to those
other classes.
There are two ways to solve this problem: Refer to all external classes by full
package name or import the appropriate class or package at the beginning of your
class file. Which one you choose to do is mostly a matter of choice, although if
you find yourself referring to a class in another package lots of times, you may
want to import it to cut down on the amount of typing.
In this example, you’ll import the classes you need. There are three of them:
Graphics, Font, and Color.
All three are part of the java.awt package. Here are the lines to import these
classes. These lines go at the
top of your program, before the actual class definition:
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;
Tip
You also can import an entire package of public classes by using an asterisk (*)
in place of a specific class name. For example, to
import all the classes in the awt package, you can use this line:
import java.awt.*;
Now, with the proper classes imported into your program, HelloAgainApplet.java
should compile cleanly to a class file. Listing 2.4 shows the final version to
double-check.
Listing 2.4. The final version of HelloAgainApplet.java.
1:import java.awt.Graphics;
2:import java.awt.Font;
3:import java.awt.Color;
4:
5:public class HelloAgainApplet extends java.applet.Applet {
6:
7: Font f = new Font(“TimesRoman”,Font.BOLD,36);
8:
9: public void paint(Graphics g) {
10: g.setFont(f);
11: g.setColor(Color.red);
12: g.drawString(“Hello again!”, 5, 40);
13: }
14:}
To test it, create an HTML file with the <APPLET> tag as you did yesterday.
Here’s an HTML file to use:
<HTML>
<HEAD>
<TITLE>Another Applet</TITLE>
</HEAD>
<BODY>
<P>My second Java applet says:
<BR><APPLET CODE=”HelloAgainApplet.class” WIDTH=200 HEIGHT=50>
</APPLET>
</BODY>
</HTML>
For this HTML example, your Java class file is in the same directory as this
HTML file. Save the file to HelloAgainApplet.html and fire up your Java-enabled
browser or the Java applet viewer. Figure 2.7 shows the result you should be
getting (the “Hello Again!” string is red).
Figure 2.7 : The HelloAgain applet.
Summary
If this is your first encounter with object-oriented programming, a lot of the
information in this lesson is going to seem really theoretical and overwhelming.
Fear not-the further along in this book you get, and the more Java classes and
applications you create, the easier it is to understand.
One of the biggest hurdles of object-oriented programming is not necessarily the
concepts; it’s their names. OOP has lots of jargon surrounding it. To summarize
today’s material, here’s a glossary of terms and concepts you learned today:
class: A template for an object, which contains variables and methods
representing behavior and
attributes. Classes can inherit variables and methods from other classes.
class method: A method defined in a class, which operates on the class itself
and can be called via the class or any of its instances.
class variable: A variable that is “owned” by the class and all its instances as
a whole and is stored in the class.
instance: The same thing as an object; each object is an instance of some class.
instance method: A method defined in a class, which operates on an instance of
that class. Instance methods are usually called just methods.
instance variable: A variable that is owned by an individual instance and whose
value is stored in the instance.
interface: A collection of abstract behavior specifications that individual
classes can then implement.
object: A concrete instance of some class. Multiple objects that are instances
of the same class have access to the same methods, but often have different
values for their instance variables.
package: A collection of classes and interfaces. Classes from packages other
than java.lang must be explicitly imported or referred to by full package name.
subclass: A class lower in the inheritance hierarchy than its parent, the
superclass. When you create a new class, it’s often called subclassing.
superclass: A class further up in the inheritance hierarchy than its child, the
subclass.
Q&A
Q: Methods are effectively functions that are defined inside classes. If they
look like functions and act like functions, why aren’t they called functions?
A: Some object-oriented programming languages do call them functions (C++ calls
them member functions). Other object-oriented languages differentiate between
functions inside and outside a body of a class or object, where having separate
terms is important to understanding how each works.
Because the difference is relevant in other languages and because the term
method is now in such common use in object-oriented technology, Java uses the
word as well.
Q: I understand instance variables and methods, but not the idea of class
variables and methods.
A: Most everything you do in a Java program will be with objects. Some behaviors
and attributes, however, make more sense if they are stored in the class itself
rather than in the object. For example, to create a new instance of a class, you
need a method that is defined and available in the class itself. (Otherwise, how
can you create an object? You need an object to call the method, but you don’t
have
an object yet.) Class variables, on the other hand, are often used when you have
an attribute whose value you want to share with all the instances of a class.
Most of the time, you’ll use instance variables and methods. You’ll learn more
about class variables and methods later this week.
Java Help, Java Tutorials, Java Programming, Java Tricks
Lesson One
What Is Java?
Java’s Past, Present, and Future
Why Learn Java?
Java Is Platform Independent
Java Is Object Oriented
Java Is Easy to Learn
Getting Started Programming in Java
Getting a Java Development Environment
Installing the JDK and Sample Files
Configuring the JDK
Creating a Java Application
Creating a Java Applet
Troubleshooting
Summary
Q&A
What exactly Java is, and its current status
Why you should learn Java-its various features and advantages over other
programming languages Getting started programming in Java-what you’ll need in
terms of software and background, as well as some basic terminology
How to create your first Java programs-to close this day, you’ll create both a
simple Java application and a simple Java applet!
What Is Java?
Based on the enormous amount of press Java is getting and the amount of
excitement it has generated, you may get the impression that Java will save the
world-or at least solve all the problems of the Internet.
Not so. Java’s hype has run far ahead of its capabilities, and while Java is
indeed new and interesting, it really is another programming language with which
you write programs that run on the Internet. In this respect, Java is closer to
popular programming languages such as C, C++, Visual Basic, or Pascal, than it
is to a page description language such as HTML, or a very simple scripting
language such as JavaScript.
More specifically, Java is an object-oriented programming language developed by
Sun Microsystems, a company best known for its high-end UNIX workstations.
Modeled after C++, the Java language was designed to be small, simple, and
portable across platforms and operating systems, both at the source and at the
binary level, which means that Java programs (applets and applications) can run
on any machine that has the Java virtual machine installed (you’ll learn more
about this later).
Java is usually mentioned in the context of the World Wide Web, where browsers
such as Netscape’s Navigator and Microsoft’s Internet Explorer claim to be “Java
enabled.” Java enabled means that the browser in question can download and play
Java programs, called applets, on the reader’s system. Applets appear in a Web
page much the same way as images do, but unlike images, applets are dynamic and
interactive. Applets can be used to create animation, figures, forms that
immediately respond to inputfrom the reader, games, or other interactive effects
on the same Web pages among the text and graphics.
Figure 1.1 shows an applet running in Netscape 3.0. (This applet, at http://prominence.com/java/poetry/,
is an electronic version of the refrigerator magnets
that you can move around to create poetry or messages.)
New Term
Applets are programs that are downloaded from the World Wide Web by a Web
browser and run inside an HTML Web page. You’ll need a Java-enabled browser such
as Netscape Navigator or Microsoft’s
Internet Explorer to run applets.
To create an applet, you write it in the Java language, compile it using a Java
compiler, and refer to that applet in your HTML Web pages. You put the resulting
HTML and Java files on a Web site in the same
way that you make ordinary HTML and image files available. Then, when someone
using a Java-enabled browser views your page with the embedded applet, that
browser downloads the applet to the local system and executes it, allowing your
reader to view and interact with your applet in all its glory. (Readers using
other browsers may see text, a static graphic, or nothing.) You’ll learn more
about how applets, browsers, and the World Wide Web work together later in this
book.
While applets are probably the most popular use of Java, the important thing to
understand about Java s that you can do so much more with it than create and use
applets. Java was written as a full-fledged general-purpose programming language
in which you can accomplish the same sorts of tasks and solve the same sorts of
problems that you can in other programming languages, such as C or C++.
Java’s Past, Present, and Future
The Java language was developed at Sun Microsystems in 1991 as part of a
research project to develop software for consumer electronics devices-television
sets, VCRs, toasters, and the other sorts of machines
you can buy at any department store. Java’s goals at that time were to be small,
fast, efficient, and easily portable to a wide range of hardware devices. Those
same goals made Java an ideal language for
distributing executable programs via the World Wide Web and also a
general-purpose programming language for developing programs that are easily
usable and portable across different platforms.
The Java language was used in several projects within Sun (under the name Oak),
but did not get very much commercial attention until it was paired with HotJava.
HotJava, an experimental World Wide Web
browser, was written in 1994 in a matter of months, both as a vehicle for
downloading and running applets and also as an example of the sort of complex
application that can be written in Java. Although HotJava got a lot of attention
in the Web community, it wasn’t until Netscape incorporated HotJava’s
ability to play applets into its own browser that Java really took off and
started to generate the excitement that it has both on and off the World Wide
Web. Java has generated so much excitement, in fact, that
inside Sun the Java group spun off into its own subsidiary called JavaSoft.
Versions of Java itself, or, as it’s most commonly called, the Java API,
correspond to versions of Sun’s Java Developer’s Kit, or JDK. As of this
writing, the current version of the JDK is 1.0.2. Previously
released versions of the JDK (alphas and betas) did not have all the features or
had a number of security-related bugs. Most Java tools and browsers conform to
the features in the 1.0.2 JDK, and all the
examples in this book run on that version as well.
The next major release of the JDK and therefore of the Java API will be 1.1,
with a prerelease version available sometime in the later part of 1996. This
release will have few changes to the language, but a
number of additional capabilities and features added to the class library.
Throughout this book, if a feature will change or will be enhanced in 1.1, we’ll
let you know, and in the last two days of this book
you’ll find out more about new Java features for 1.1 and for the future.
Currently, to program in Java, you’ll need a Java development environment of
some sort for your platform. Sun’s JDK works just fine for this purpose and
includes tools for compiling and testing Java
applets and applications. In addition, a wide variety of excellent Java
development environments have been developed, including Sun’s own Java Workshop,
Symantec’s Café, Microsoft’s Visual J++ (which is
indeed a Java tool, despite its name), and Natural Intelligence’s Roaster, with
more development tools appearing all the time.
To run and view Java applets, you’ll need a Java-enabled browser or other tool.
As mentioned before, recent versions of Netscape Navigator (2.0 and higher) and
Internet Explorer (3.0) can both run Java
applets. (Note that for Windows you’ll need the 32-bit version of Netscape, and
for Macintosh you’ll need Netscape 3.0.) You can also use Sun’s own HotJava
browser to view applets, as long as you have the 1.0
prebeta version (older versions are not compatible with newer applets, and vice
versa). Even if you don’t have a Java-enabled browser, many development tools
provide simple viewers with which you can run
your applets. The JDK comes with one of these; it’s called the appletviewer.
Note
If you’re running Windows 3.x as your main system, very few toolsexist for you
to be able to work with Java. As I write this, the only
Java tool available for writing and running Java applets is a version ofthe JDK
from IBM called the ADK. You can write applets using this
tool, and view them using the applet viewer that comes with thatpackage (neither
Netscape nor Internet Explorer will run Java applets
on Windows 3.1). See http://www.alphaWorks.ibm.com/ for more information.
What’s in store for Java in the future? A number of new developments have been
brewing (pardon the
pun):
Sun is developing a number of new features for the Java environment, including a
number of new class libraries for database integration, multimedia, electronic
commerce, and other uses. Sun also
has a Java-based Web server, a Java-based hardware chip (with which you can
write Java-specific systems), and a Java-based operating system. You’ll learn
about all these things later in this book.
The 1.1 release of the JDK will include many of these features; others will be
released as separate
packages.
Sun is also developing a framework called Java Beans, which will allow the
development of component objects in Java, similarly to Microsoft’s ActiveX (OLE)
tech-nology. These different
components can then be easily combined and interact with each other using
standard component assembly tools. You’ll learn more about Java Beans later in
this book.
Java capabilities will be incorporated into a wide variety of operating systems,
including Solaris, Windows 95, and MacOS. This means that Java applications (as
opposed to applets) can run nearly
anywhere without needing additional software to be installed.
Many companies are working on performance enhancements for Java programs,
including the aforementioned Java chip and what are called just-in-time
compilers.
Why Learn Java?
At the moment, probably the most compelling reason to learn Java-and probably
the reason you bought this book-is that applets are written in Java. Even if
that were not the case, Java as a programming
language has significant advantages over other languages and other environments
that make it suitable for just about any programming task. This section
describes some of those advantages.
Java Is Platform Independent Platform independence-that is, the ability of a
program to move easily from one computer system to
another-is one of the most significant advantages that Java has over other
programming languages, particularly if your software needs to run on many
different platforms. If you’re writing software for the
World Wide Web, being able to run the same program on many different systems is
crucial to that program’s success. Java is platform independent at both the
source and the binary level.
New Term
Platform independence means that a program can run on anycomputer system. Java
programs can run on any system for which a Java virtual machine has been
installed.
At the source level, Java’s primitive data types have consistent sizes across
all development platforms. Java’s foundation class libraries make it easy to
write code that can be moved from platform to platform
without the need to rewrite it to work with that platform. When you write a
program in Java, you don’t need to rely on features of that particular operating
system to accomplish basic tasks. Platform
independence at the source level means that you can move Java source files from
system to system and have them compile and run cleanly on any system.
Platform independence in Java doesn’t stop at the source level, however. Java
compiled binary files are also platform independent and can run on multiple
platforms (if they have a Java virtual machine
available) without the need to recompile the source.
Normally, when you compile a program written in C or in most other languages,
the compiler translates your program into machine code or processor
instructions. Those instructions are specific to the
processor your computer is running-so, for example, if you compile your code on
an Intel-based system,the resulting program will run only on other Intel-based
systems. If you want to use the same program on
another system, you have to go back to your original source code, get a compiler
for that system, and recompile your code so that you have a program specific to
that system. Figure 1.2 shows the result of
this system: multiple executable programs for multiple systems.
Things are different when you write code in Java. The Java development
environment actually has two parts: a Java compiler and a Java interpreter. The
Java compiler takes your Java program and, instead of
generating machine codes from your source files, it generates bytecodes.
Bytecodes are instructions that look a lot like machine code, but are not
specific to any one processor.
To execute a Java program, you run a program called a bytecode interpreter,
which in turn reads the bytecodes and executes your Java program (see Figure
1.3). The Java bytecode interpreter is often also
called the Java virtual machine or the Java runtime.
New Term
Java bytecodes are a special set of machine instructions that are notspecific to
any one processor or computer system. A platform-specific bytecode interpreter
executes the Java bytecodes. The bytecodeinterpreter is also called the Java
virtual machine or the Java runtime
interpreter.
Where do you get the bytecode interpreter? For applets, the bytecode interpreter
is built into every Java-enabled browser, so you don’t have to worry about
it-Java applets just automatically run. For more
general Java applications, you’ll need to have the interpreter installed on your
system in order to run that Java program. Right now, you can get the Java
interpreter as part of your development environment, or if
you buy a Java program, you’ll get it with that package. In the future, however,
the Java bytecode interpreter will most likely come with every new operating
system-buy a Windows machine, and you’ll
get Java for free.
Why go through all the trouble of adding this extra layer of the bytecode
interpreter? Having your Java programs in bytecode form means that instead of
being specific to any one system, your programs can be
run on any platform and any operating or window system as long as the Java
interpreter is available. This capability of a single binary file to be
executable across platforms is crucial to what makes applets work
because the World Wide Web itself is also platform independent. Just as HTML
files can be read on any platform, so can applets be executed on any platform
that has a Java-enabled browser.
The disadvantage of using bytecodes is in execution speed. Because
system-specific programs run directly on the hardware for which they are
compiled, they run significantly faster than Java bytecodes,
which must be processed by the interpreter. For many basic Java programs, speed
may not be an issue. If you write programs that require more execution speed
than the Java interpreter can provide, you have
several solutions available to you, including being able to link native code
into your Java program or using special tools (called just-in-time compilers) to
convert your Java bytecodes into native code and
speed up their execution. Note that by using any of these solutions, you lose
the portability that Java bytecodes provide. You’ll learn about each of these
mechanisms on Day 20, “Using Native Methods and
Libraries.”
Java Is Object Oriented
To some, the object-oriented programming (OOP) technique is merely a way of
organizing programs, and it can be accomplished using any language. Working with
a real object-oriented language and
programming environment, however, enables you to take full advantage of
object-oriented methodology and its capabilities for creating flexible, modular
programs and reusing code.
Many of Java’s object-oriented concepts are inherited from C++, the language on
which it is based, but it borrows many concepts from other object-oriented
languages as well. Like most object-oriented
programming languages, Java includes a set of class libraries that provide basic
data types, system input and output capabilities, and other utility functions.
These basic libraries are part of the standard Java
environment, which also includes simple libraries, form networking, common
Internet protocols, and user interface toolkit functions. Because these class
libraries are written in Java, they are portable across
platforms as all Java applications are.
You’ll learn more about object-oriented programming and Java tomorrow.
Java Is Easy to Learn
In addition to its portability and object orientation, one of Java’s initial
design goals was to be small and simple, and therefore easier to write, easier
to compile, easier to debug, and, best of all, easy to learn.
Keeping the language small also makes it more robust because there are fewer
chances for programmers to make mistakes that are difficult to fix. Despite its
size and simple design, however, Java still has a
great deal of power and flexibility.
Java is modeled after C and C++, and much of the syntax and object-oriented
structure is borrowed from the latter. If you are familiar with C++, learning
Java will be particularly easy for you because you have
most of the foundation already. (In fact, you may find yourself skipping through
the first week of this book fairly rapidly. Go ahead; I won’t mind.)Although
Java looks similar to C and C++, most of the more complex parts of those
languages have been
excluded from Java, making the language simpler without sacrificing much of its
power. There are no pointers in Java, nor is there pointer arithmetic. Strings
and arrays are real objects in Java. Memory
management is automatic. To an experienced programmer, these omissions may be
difficult to get used to, but to beginners or programmers who have worked in
other languages, they make the Java language
far easier to learn.
However, while Java’s design makes it easier to learn than other programming
languages, working with a programming language is still a great deal more
complicated than, say, working in HTML. If you have
no programming language background at all, you may find Java difficult to
understand and to grasp. But don’t be discouraged! Learning programming is a
valuable skill for the Web and for computers in
general, and Java is a terrific language to start out with.
Getting Started Programming in JavaEnough background! For the second half of
this day let’s actually dive into simple Java programming and
create two Java programs: a standalone Java application and an applet that you
can view in a Java-enabled browser. Although both these programs are extremely
simple, they will give you an idea of
what a Java program looks like and how to compile and run it.
Getting a Java Development Environment In order to write Java programs, you
will, of course, need a Java development environment. (Although
browsers such as Netscape allow you to play Java applets, they don’t let you
write them. For that you’ll need a separate tool.) Sun’s JDK, which is available
for downloading at the JavaSoft Web site
(http://www.javasoft.com/) and included on the CD for this book, will do just
fine. It runs on Solaris, Windows 95 and NT, and Macintosh. However, despite the
JDK’s popularity, it is not the easiest
development tool to use. If you’re used to using a graphical user
interface-based development tool with an integrated editor and debugger, you’ll
most likely find the JDK’s command-line interfaces rather
primitive. Fortunately, the JDK is not the only tool in town.
As mentioned earlier, a number of third-party development environments (called
integrated development environments, or IDEs) are also available for developing
in Java. These include Sun’s Java Workshop for
Solaris, Windows NT and Windows 95 (you can get more information about it athttp://www.sun.com/developer-products/java/);
Symantec’s Café for Windows 95,
Windows NT, and Macintosh (http://cafe.symantec.com/); Microsoft’s Visual J++
forWindows 95 and Windows NT (http://www.microsoft.com/visualj/); and Natural
Intelligence’s Roaster(http://www.natural.com/pages/products/roaster/index.html).
All three are
commercial programs, but you might be able to download trial or limited versions
of these programs to
try them out. You’ll learn more about the features and capabilities of the
various Java IDEs on Day 22,
“Java Programming Tools.”
Note
I find the graphical development environments far easier to use than
the standard JDK. If you have the money and the time to invest in one
of these tools, I highly recommend you do so. It’ll make your Java
development experience much more pleasant.
Installing the JDK and Sample Files
Sun’s JDK for Solaris, Windows, and Macintosh is included as part of the CD-ROM
that comes with this
book. Also on the CD-ROM are all of the code examples from this book-a great
help if you don’t want to
type them all in again. To install either the JDK or the sample files (or both),
use one of the following
procedures:
Note
If you don’t have access to a CD-ROM drive, you can also get accessto these
files over the World Wide Web. You can download the JDK
itself from http://java.sun.com/products/JDK/1.0.2/and install it per the
instructions on those pages. The sample files
from this book are available on the Web site for this book:http://www.lne.com/Web/JavaProf/.
If you download the JDK and source files, as opposed to getting themoff the
CD-ROM, make sure you read the section “Configuring the
JDK” to make sure everything is set up right.Windows Sun’s JDK runs on Windows
95 and Windows NT. It does not run on
Windows 3.x.
To install the JDK or the sample files on Windows, run the Setup program on the
CD-ROM
(double-clicking the CD icon will do this automatically). By default, the
package will be installed into
C:\Java; you can install it anywhere on your hard disk that you’d like. You’ll
be given options to install
the JDK, the sample files, and various other extra files; choose the options you
want and those files will
be installed.
If you’ve installed the JDK, note that in the directory JDK\lib there is a file
called classes.zip. Do
not unzip this file; it needs to remain in zip form for it to work correctly.
The file JDK\src.zip
contains the source code for many of the JDK libraries; you can unzip this one
if you like. Make sure if
you do that you have a zip program that supports long filenames, or it will not
work correctly!
Macintosh
Sun’s JDK for Macintosh runs on System 7 (MacOS) for 68KB or
Power Mac.
To install the JDK or the sample files on the Macintosh, double-click the
installation program on the
CD-ROM. By default, the package will be installed into the folder Java on your
hard disk; you can
install it anywhere on your disk that you’d like. You’ll be given options to
install the JDK, the sample
files, and various other extra files; choose the options you want and those
files will be installed.
Solaris
Sun’s JDK for Solaris runs on Solaris 2.3, 2.4, and 2.5, as well as the
x86 version of Solaris.
The CD-ROM for this book contains the tarred and zipped JDK in the directory
jdk/solaris/jdk1.02.tgz. Using the utilities gunzip and tar, you can extract the
contents of
that file anywhere on the file system you would like. For example, if you copy
the .tgz file to your
home directory and use the following commands to extract it, you’ll end up with
a java directory that
contains the full JDK:
gunzip ./jdk1.02.tgz
tar xvf ./jdk1.02.tar
Note that in the directory java\lib there is a file called classes.zip. Do not
unzip this file; it
needs to remain in zip form for it to work correctly. The file java\src.zip
contains the source code
for many of the JDK libraries; you can unzip this one if you’re interested in
the source code.
The sample files are also contained on the CD-ROM in authors/authors.tar. Create
a directory
where the sample files will live (for example, a directory called javasamples in
your home directory),
copy the authors.tar file there, and then use the tar command to extract it,
like this:
mkdir ~/javasamples
cp /cdrom/authors/authors.tar
tar xvf authors.tar
Configuring the JDK
If you’ve installed the JDK using the setup programs from the CD-ROM, chances
are good that it has
been correctly configured for you. However, because most common problems with
Java result from
configuration errors, I recommend that you double-check your configuration to
make sure everything is
right. And if you’ve installed the JDK from a source other than the CD-ROM,
you’ll definitely want to
read this section to make sure you’re all set up.
Windows
The JDK needs two important modifications to yourautoexec.bat file in order to
work correctly: The JDK\bin
directory must be in your execution path, and you must have the CLASSPATH
variable set up.
Edit your autoexec.bat file using your favorite editor (Notepad will do just
fine). Look for a line
that looks something like this:
PATH C:\WINDOWS;C:\WINDOWS\COMMAND;C:\DOS; …
Somewhere in that line you should see an entry for the JDK; if you installed the
JDK from CD-ROM, it’ll
look something like this (the dots are there to indicate that there may be other
stuff on this line):
PATH C:\WINDOWS; … C:\TEAchY~1\JDK\BIN; …
If you cannot find any reference to JDK\BIN or JAVA\BIN in your PATH, you’ll
need to add it. Simply
include the full pathname to your JDK installation to the end of that line,
starting with C: and ending
with BIN; for example, C:\JAVA\BIN or C:\Java\JDK\BIN.
Note
The directories Teach Yourself Java and TEAchY~1 are
actually the same thing; the former is how the directory appears in
Windows 95, and the latter is how it appears in DOS. Either one will
work fine; there’s no need to change it if one or the other appears.
Note, however, that if the pathname contains spaces, it must be in
quotes.
The second thing you’ll need to add to the autoexec.bat file (if it isn’t
already there) is a
CLASSPATH variable. Look for a line that looks something like this:
SET CLASSPATH=C:\TEAchY~1\JDK\lib\classes.zip;.;The CLASSPATH variable may also
have other entries in it for Netscape or Internet Explorer, but the one
you’re most interested in is a reference to the classes.zip file in the JDK, and
to the current
directory (.). If your autoexec.bat file does not include either of these
locations, add a line to the
file that contains both these things (the line shown above will work just fine).
After saving your autoexec.bat file, you’ll need to restart Windows for the
changes to take effect.
Macintosh
The JDK for Macintosh should need no further configuration after
installation.
Solaris
To configure the JDK for Solaris, all you need to do is add the
java/bin or jdk/bin directory to your execution path. Usually a
line something like this in your .cshrc, .login, or .profile
files will work:
set path= (~/java/bin/ $path)
This line assumes that you’ve installed the JDK (as the directory java) into
your home directory; if
you’ve installed it somewhere else, you’ll want to substitute that pathname.
Make sure you use the source command with the name of the appropriate file to
make sure the changes
take effect (or log out and log back in again):
source ~/.login
Creating a Java Application
Now let’s actually get to work. We’ll start by creating a simple Java
application: the classic Hello World
example that many programming language books use to begin.
Java applications are different from Java applets. Applets, as you have learned,
are Java programs that
are downloaded over the World Wide Web and executed by a Web browser on the
reader’s machine.
Applets depend on a Java-enabled browser in order to run.
New Term
Java applications, however, are more general programs written in the
Java language. Java applications don’t require a browser to run; in
fact, Java can be used to create all the kinds of applications that you
would normally use a more conventional programming language tocreate.
Java applications are standalone Java programs that do not require a Web browser
to run. Java
applications are more general-purpose programs such as you’d find on any
computer.
A single Java program can be an applet or an application, or both, depending on
how you write that
program and the capabilities that program uses. Throughout this first week as
you learn the Java
language, you’ll be writing mostly applications; then you’ll apply what you’ve
learned to write applets in
Week 2. If you’re eager to get started with applets, be patient. Everything that
you learn while you’re
creating simple Java applications will apply to creating applets, and it’s
easier to start with the basics
before moving onto the hard stuff. You’ll be creating plenty of applets in Week
2.Creating the Source File
As with all programming languages, your Java source files are created in a plain
text editor, or in an
editor that can save files in plain ASCII without any formatting characters. On
UNIX, emacs, pico,
and vi will work; on Windows, Notepad or DOS Edit are both text editors that
will work (although I
prefer to use the shareware TextPad). On the Macintosh, SimpleText (which came
with your Mac) or the
shareware BBedit will work. If you’re using a development environment like Café
or Roaster, it’ll have
its own built-in text editor you can use.
Note
If you’re using Windows to do your Java development, you may have
to make sure Windows understands the .java file extension before
you start; otherwise, your text editor may insist on giving all your
files a .txt extension. The easiest way to do this is to go to any
Windows Explorer window, choose View|Options|File Types, choose
New Type, and add Java Source File and .java to the
Description of Type and Associated Extension boxes, respectively.
Fire up your editor of choice and enter the Java program shown in Listing 1.1.
Type this program, as
shown, in your text editor. Be careful that all the parentheses, braces, and
quotes are there, and that
you’ve used all the correct upper- and lowercase letters.
Note
You can also find the code for these examples on the CD-ROM as
part of the sample code. However, it’s a good idea to actually type
these first few short examples in so that you get a feel for what Java
code actually looks like.
Listing 1.1. Your first Java application.
1: class HelloWorld {
2: public static void main (String args[]) {
3: System.out.println(“Hello World!”);
4: }
5: }
Warning
The number before each line is part of the listing and not part of the
program; the numbers are there so I can refer to specific line numbers
when I explain what’s going on in the program. Do not include them
in your own file.
After you’ve finished typing in the program, save the file somewhere on your
disk with the name
HelloWorld.java. This is very important. Java source files must have the same
name as the class
they define (including the same upper- and lowercase letters), and they must
have the extension .java.
Here, the class definition has the name HelloWorld, so the filename must be
HelloWorld.java. If
you name your file something else (even something like helloworld.java or
Helloworld.java), you won’t be able to compile it. Make absolutely certain the
name isHelloWorld.java.
You can save your Java files anywhere you like on your disk, but I like to have
a central directory or
folder to keep them all in. For the examples in this chapter, I’ve put my files
into a directory called
TYJtests (short for Teach Yourself Java Tests).
Compiling and Running the Source File
Now it’s time to compile the file. If you’re using the JDK, you can use the
instructions for your computer
system contained in the next few pages. If you’re using a graphical development
environment, there will
most likely be a button or option to compile the file (check with the
documentation that came with your
program).
Windows
To compile the Java source file, you’ll use the command-line Java
compiler that comes with the JDK. To run the compiler, you’ll need to
first start up a DOS shell. In Windows 95, the DOS shell is under the
Programs menu (it’s called MS-DOS Prompt).
From inside DOS, change directories to the l
ocation where you’ve saved your HelloWorld.java file.
I put mine into the directory TYJtests, so to change directories I’d use this
command:
CD C:\TYJtests
Once you’ve changed to the right directory, use the javac command as follows,
with the name of the
file as you saved it in Windows (javac stands for Java compiler). Note that you
have to make sure you
type all the same upper- and lowercase here as well:
javac HelloWorld.java
Note
The reason that I’ve emphasized using the original filename is that
once you’re inside the DOS shell, you might notice that your nice
long filenames have been truncated to old-style 8.3 names and that, in
fact, HelloWorld.java actually shows up as HELLOW~1.jav.
Don’t panic; this is simply a side effect of Windows 95 and how it
manages long filenames. Ignore the fact that the file appears to be
HELLOW~1.jav and just use the filename you originally used when you saved the
file.
Figure 1.4 shows what I’ve done in the DOS shell so you can make sure you’re
following along.
Figure 1.4 : Compiling Java in the DOS shell.
If all goes well, you’ll end up with a file called HelloWorld.class (or at least
that’s what it’ll be
called if you look at it outside the DOS shell; from inside DOS its called
HELLOW~1.cla). That’s your
Java bytecode file. If you get any errors, go back to your original source file
and make sure you typed it
exactly as it appears in Listing 1.1 with the same upper- and lowercase. Also
make sure the filename has
exactly the same upper- and lowercase as the name of the class (that is, both
should be HelloWorld).
Once you have a class file, you can run that file using the Java bytecode
interpreter. The Java interpreter
is called simply java, and you run it from the DOS shell as you did javac. Run
your Hello World
program like this from the command line, with all the same upper- and lowercase
(and note that the
argument to the java program does not have a .class extension):
java HelloWorld
If your program was typed and compiled correctly, you should get the phrase
Hello World! printed
to your screen as a response. Figure 1.5 shows how I did it.
Figure 1.5 : Running Java applications in the DOS shell.
Note
Remember, the Java compiler and the Java interpreter are different
things. You use the Java compiler (javac) for your Java source files
to create .class files, and you use the Java interpreter (java) to
actually run your class files.
Macintosh
The JDK for the Mac comes with an application called Java
Compiler. To compile your Java source file, simply drag and drop it
on top of the Java Compiler icon. The program will compile your
Java file and, if there are no errors, create a file called
HelloWorld.class in the same folder as your original source
file.
Tip
Putting an alias for Java Compiler on the desktop makes it easy to
drag and drop Java source files.
If you get any errors, go back to your original source file and make sure you
typed it exactly as it appears
in Listing 1.1, with the same upper- and lowercase. Also make sure the filename
has exactly the same
upper- and lowercase as the name of the class (that is, both should be
HelloWorld).
Once you’ve successfully generated a HelloWorld.class file, simply double-click
it to run it. The
application Java Runner, part of the Mac JDK, will start, and the program will
ask you for command-line
arguments. Leave that screen blank and click OK. A window labeled stdout will
appear with the
message Hello World!. Figure 1.6 shows that window.
Figure 1.6 : Running Java applications on the Mac using Java Runner.
That’s it! Keep in mind as you work that you use the Java Compiler application
to compile your .java
files into .class files, which you can then run using Java Runner.
To compile the Java source file in Solaris, you’ll use the command-line Java
compiler that comes with the
JDK. From a UNIX command line, cd to the directory that contains your Java
source file. I put mine in
the directory TYJtests, so to change directories I’d use this command:
cd ~/TYJtests
Once you’re in the right directory, use the javac command with the name of the
file, like this:
javac HelloWorld.java
If all goes well, you’ll end up with a file called HelloWorld.class in the same
directory as your
source file. That’s your Java bytecode file. If you get any errors, go back to
your original source file and
make sure you typed it exactly as it appears in Listing 1.1, with the same
upper- and lowercase letters.
Also make sure the filename has exactly the same upper- and lowercase letters as
the name of the class
(that is, both should be HelloWorld).
Once you have a class file, you can run that file using the Java bytecode
interpreter. The Java interpreter
is called simply java, and you run it from the command line as you did javac,
like this (and note that
the argument to the java program does not have a .class extension):
java HelloWorld
If your program was typed and compiled correctly, you should get the phrase
Hello World! printed
to your screen as a response. Figure 1.7 shows a listing of all the commands I
used to get to this point
(the part with [desire]~[1] is my system prompt).
Figure 1.7 : Compiling and running a Java application on Solaris.
Note
Remember that the Java compiler and the Java interpreter are
different things. You use the Java compiler (javac) for your Java
source files to create .class files, and you use the Java interpreter
(java) to actually run your class files.
Creating a Java Applet
Creating applets is different from creating a simple application. Java applets
run and are displayed inside
a Web page with other page elements, and therefore have special rules for how
they behave. Because of
these special rules for applets, creating an applet may in many cases be more
complex than creating an
application.
For example, to create a simple Hello World applet, instead of merely being able
to print a message as a
set of characters, you have to make space for your message on the Web pages and
then use special font
and graphics operations to paint the message to the screen.
Note
Actually, you can run a plain Java application as an applet, but the
Hello World message will print to a special window or to a log
file, depending on how the browser has its output set up. You’ll learn
more about this next week.
Creating the Source File
In this example, you’ll create a simple Hello World applet, place it inside a
Web page, and view the
result. As with the Hello World application, you’ll first create the source file
in a plain text editor. Listing
1.2 shows the code for the example.
Listing 1.2. The Hello World applet.
1: import java.awt.Graphics;
2:
3: public class HelloWorldApplet extends java.applet.Applet {
4:
5: public void paint(Graphics g) {
6: g.drawString(“Hello world!”, 5, 25);
7: }
8:}
Save that file just as you did the Hello World application, with the filename
exactly the same as the name
of the class. In this case the class name is HelloWorldApplet, so the filename
you save it to would
be HelloWorldApplet.java. As with the application, I put the file in a directory
called TYJch01,
but you can save it anywhere you like.
Compiling the Source File
The next step is to compile the Java applet file. Despite the fact that this is
an applet, you compile the file
exactly the same way you did the Java application, using one of the following
procedures:
javac HelloWorldApplet.java
javac HelloWorldApplet.java
Windows
From inside a DOS shell, cd to the directory containing your applet
source file, and use the javac command to compile it (watch those
upper- and lowercase letters):
Macintosh
Drag and drop the HelloWorldApplet.java file onto the Java
Compiler icon.
Salaris
From a command line, cd to the directory containing your applet
source file and use the javac command to compile it:
Including the Applet in a Web Page
If you’ve typed the file correctly, you should end up with a file called
HelloWorldApplet.class in
the same directory as your source file. That’s your Java applet file; to have
the applet run inside a Web
page you must refer to that class file inside the HTML code for that page using
the <APPLET> tag.
Listing 1.3 shows a simple HTML file you can use.
Listing 1.3. The HTML with the applet in it.
1: <HTML>
2: <HEAD>
3: <TITLE>Hello to Everyone!</TITLE>
4: </HEAD><BODY>
5: <P>My Java applet says:
6: <APPLET CODE=”HelloWorldApplet.class” WIDTH=150 HEIGHT=25>
7: </APPLET>
8: </BODY>
9: </HTML>
You’ll learn more about <APPLET> later in this book, but here are two things to
note about it:
Use the CODE attribute to indicate the name of the class that contains your
applet, here
HelloWorldApplet.Class.
Use the WIDTH and HEIGHT attributes to indicate the size of the applet on the
page. The browser
uses these values to know how big a chunk of space to leave for the applet on
the page. Here, a
box 150 pixels wide and 25 pixels high is created.
Save the HTML file in the same directory as your class file, with a descriptive
name and an .html
extension (for example, you might name your HTML file the same name as your
applet-HelloWorldApplet.html).
Note
As mentioned earlier with the Java source files, your text editor may
insist on naming your HTML files with a .txt extension if Windows
does not understand what the .html extension is used for. Select
View|Options|File Types from any Windows Explorer window to add
a new file type for HTML files to solve this problem.
Now you’re ready for the final test-actually viewing the result of running your
applet. To view the applet,
you need one of the following:
A browser that supports Java applets, such as Netscape 2.0 or Internet Explorer
3.0. If you’re
running on the Macintosh, you’ll need Netscape 3.0 or later. If you’re running
on Windows 95 or
NT, you’ll need the 32-bit version of Netscape. And if you’re using Internet
Explorer, you’ll need
the 3.0 beta 5 or later (the final version will do just fine).
The appletviewer application, which is part of the JDK. The appletviewer is not
a Web
browser and won’t let you to see the entire Web page, but it’s acceptable for
testing to see how an
applet will look and behave if there is nothing else available.
An applet viewer or runner tool that comes with your development environment.
If you’re using a Java-enabled browser such as Netscape to view your applet
files, you can use the Open
File… item under the File menu to navigate to the HTML file containing the
applet (make sure you open
the HTML file and not the class file). In Internet Explorer, select File|Open
and then Browse to find the
file on your disk. You don’t need to install anything on a Web server yet; all
this works on your local
system. Note that the Java applet may take a while to start up after the page
appears to be done loading;
be patient. Figure 1.8 shows the result of running the applet in Netscape.
Figure 1.8 : The applet running in Netscape.
If you don’t have a Web browser with Java capabilities built into it, you can
use the JDK’s
appletviewer program to view your Java applet.
appletviewer HTML/HelloWorldApplet.html
Windows or Solaris
To run the appletviewer in Windows or Solaris versions of the JDK, cd to the
directory where your HTML and class files are contained and use the appletviewer
command with the name ofthe HTML file you just created:
The appletviewer will show you only the applet itself, not the HTML text around
the applet.
Although the appletviewer is a good way to do simple tests of Java applets, it’s
a better idea to get a
Java-enabled browser so that you can see your applet on its page in its full
glory.
Troubleshooting
If you’ve run into any problems with the previous examples, this section can
help. Here are some of the
most common problems and how to fix them:
Bad command or filename or Command not found
These errors result when you do not have the JDK’s bin directory in your
execution path, or the
path to that directory is wrong. On Windows, double-check your autoexec.bat
file; on UNIX,
check the system file with your path commands in it (.cshrc, .login, .profile,
or some
similar file).
javac: invalid argument
Make sure the name of the file you’re giving to the javac command is exactly the
same name as
the file. In particular, in the DOS shell you want to use the Windows filename
with a .java
extension, not the DOS equivalent (HELLOW~1.jav, for example).
Warning: public class HelloWorldApplet must be defined in a file
called HelloWorldApplet.java
This error most often happens if there is a mismatch between the name of the
class as defined in
the Java file itself (the name following the word class) and the name of the
java source file. Both
the filenames must match, including upper- and lowercase letters (this
particular error implies that
the filename had lowercase letters). Rename either the filename or the class
name, and this error
will go away.
Insufficient-memory errors
The JDK is not the most efficient user of memory. If you’re getting errors about
memory, consider
closing larger programs before running Java compiles, turn on virtual memory, or
install more RAM.
Other code errors
If you’re unable to compile the Java source files because of other errors I
haven’t mentioned here,
be sure that you’ve typed them in exactly as they appear, including all upper-
and lowercase letters.
Java is case sensitive, meaning that upper- and lowercase letters are treated
differently, so you will
need to make sure that everything is capitalized correctly. If all else fails,
try comparing your
source files to the files on the CD-ROM.
Summary
Today you’ve gotten a basic introduction to the Java language and its goals and
features. Java is a
programming language, similar to C or C++, in which you can develop a wide range
of programs. The
most common use of Java at the moment is in creating applets for HotJava, an
advanced World Wide
Web browser also written in Java. Applets are Java programs that are downloaded
and run as part of a
Web page. Applets can create animation, games, interactive programs, and other
multimedia effects on
Web pages.
Java’s strengths lie in its portability-both at the source and at the binary
level, in its object-oriented
design-and in its simplicity. Each of these features helps make applets
possible, but they also make Java
an excellent language for writing more general-purpose programs that do not
require a Java-enabled
browser to run. These general-purpose Java programs are called applications.
To end this day, you experimented with an example of an applet and an example of
an application,
getting a feel for the differences between the two and how to create, compile,
and run Java programs-or,
in the case of applets, how to include them in Web pages. From here, you now
have the foundation to
create more complex applications and applets. Onward to Day 2, “Object-Oriented
Programming and
Java”!
Q&A
Q: I know a lot about HTML, but not much about computer programming. Can I still
write
Java programs?
A: If you have no programming experience whatsoever, you most likely will find
programming
Java significantly more difficult than HTML. However, Java is an excellent
language to learn
programming with, and if you patiently work through the examples and the
exercises in this
book, you should be able to learn enough to get started with Java.
Q: What’s the relationship between JavaScript and Java?
A: They have the same first four letters.
A common misconception in the Web world today is that Java and JavaScript have
more in
common than they actually do. Java is the general-purpose programming language
that you’ll
learn about in this book; you use it to create applets. JavaScript is a
Netscape-invented scripting
language that looks sort of like Java; with it you can do various nifty things
in Web pages. They
are independent languages, used for different purposes. If you’re interested in
JavaScript
programming, you’ll want to pick up another book, such as Teach Yourself
JavaScript in a Week
or Laura Lemay’s Web Workshop: JavaScript, both also available from Sams.net
Publishing.
Q: According to today’s lesson, Java applets are downloaded via a Java-enabled
browser such
as Netscape and run on the reader’s system. Isn’t that an enormous security
hole? What
stops someone from writing an applet that compromises the security of my
system-or
worse, that damages my system?
A: Sun’s Java team has thought a great deal about the security of applets within
Java-enabled
browsers and has implemented several checks to make sure applets cannot do nasty
things:
Java applets cannot read or write to the disk on the local system.
Java applets cannot execute any programs on the local system.
Java applets cannot connect to any machines on the Web except for the server
from which
they are originally downloaded.
Note that some of these restrictions may be allowed in some browsers or may be
turned on in the
browser configuration. However, you cannot expect any of these capabilities to
be available.
In addition, the Java compiler and interpreter check both the Java source code
and the Java
bytecodes to make sure that the Java programmer has not tried any sneaky tricks
(for example,
overrunning buffers or stack frames).
These checks obviously cannot stop every potential security hole (no system can
promise that!),
but they can significantly reduce the potential for hostile applets. You’ll
learn more about
security issues for applets on Day 8, “Java Applet Basics,” and in greater
detail on Day 21,
“Under the Hood.”
Q: I followed all the directions you gave for creating a Java applet. I loaded
it into HotJava,but Hello World didn’t show up. What did I do wrong?
A: Don’t use HotJava to view applets you’ve created in this book; get a more
up-to-date browsersuch as Netscape or Internet Explorer. HotJava was an
experimental browser and has not beenupdated since soon after its original
release. The steps you take to define and write an applethave changed since
then, and the applets you write now will not run on HotJava.
Q: You’ve mentioned Solaris, Windows, and Macintosh in this chapter. What about
otheroperating systems?
A: If you use a flavor of UNIX other than Solaris, chances are good that the JDK
has been ported to your system. Here are some examples:
SGI’s version of the JDK can be found at
http://www.sgi.com/Products/cosmo/cosmo_instructions.html.
Information about Java for Linux can be found at
http://www.blackdown.org/java-linux/.
IBM has ported the JDK to OS/2 and AIX. Find out more from
http://www.ncc.hurley.ibm.com/javainfo/.
OSF is porting the JDK to HP/UX, Unixware, Sony NEWS, and Digital UNIX. See
http://www.osf.org/mall/web/javaport.htm.
(Thanks to Elliote Rusty Harold’s Java FAQ at
http://www.sunsite.unc.edu/javafaq/javafaq/html for this information.)
Q: Why doesn’t Java run on Windows 3.1?
A: Technical limitations in Windows 3.1 make porting Java to Windows 3.1
particularly difficult.Rumor has it that both IBM and Microsoft are working on
ports, but no real information is forthcoming.
Q: I’m using Notepad on Windows to edit my Java files. The program insists on
adding a.txt extension to all my files, regardless of what I name them (so I
always end up with files like HelloWorld.java.txt). Short of renaming them
before I compile them, what else can I do to fix this?
A: Although you can rename the files just before you compile them, that can get
to be a pain, particularly when you have a lot of files. The problem here is
that Windows doesn’t understand the .java extension (you may also have this
problem with HTML’s .html extension as well). To fix this, go into any Windows
Explorer window and select View|Options|File Types. Fromthat panel, select New
Type. Enter Java Source Files in the Description of Type box and .java into the
Associated Extension box. Then click OK. Do the same with HTML files if you need
to, and click OK again. You should now be able to use Notepad (or any other text
editor) to create and save Java and HTML files.
Q: Where can I learn more about Java and find applets and applications to play
with?
A: You can read the rest of this book! Here are some other places to look for
Java information and Java applets:
The Java home page at http://www.java.sun.com/ is the official source for Java
information, including information about the JDK, about the upcoming 1.1
release, and about developer tools such as the Java Workshop, as well as
extensive documentation.
Gamelan, at http://www.gamelan.com/, is a repository of applets and Java
information, organized into categories. If you want to play with applets or
applications, this is the place to look.
For Java discussion, check out the comp.lang.java newsgroups, including
comp.lang.java.programmer, comp.lang.java.tech,
comp.lang.java.advocacy, and so on. (You’ll need a Usenet newsreader to access
-
Recent
- Windows Shortcut Keys
- DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP PART-03
- DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP 02
- DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP 01
- Valentine Gifts & Valentine Jewelry
- Java Help, Java Tutorials, Java Programming, Java Tricks
- Java Help, Java Tutorials, Java Programming, Java Tricks
- Java Help, Java Tutorials, Java Programming, Java Tricks
- Java Help, Java Tutorials, Java Programming, Java Tricks
- C Language Help, C Language Tutorials, C Language Programming, C Language Tricks { The C# Language }
- C Language Help, C Language Tutorials, C Language Programming, C Language Tricks { The C# Language }
- C Language Help, C Language Tutorials, C Language Programming, C Language Tricks { The C# Language }
-
Links
- Sherawat Building Construction Jaipur
- Web Designing Company Jaipur
- world news update
- It Education
- it education video
- hindi online movie
- rajasthan election 2008
- rajasthan election
- Diamond Jewelry,Diamond Rings,Diamond Engagement Rings,Diamond Earrings,Diamond Pendants at DiamondJewelry4u.
- Tourism oF Rajasthan
- World News Update
- EDUCATION HEALTH CARE
- Rajasthan Tourism
- Best Songs
- Information Technology Education
- Rajasthan Election 2008
- Information Technology Video Education
- IT Service
- Web Solution
- SHERAWAT WEB SOLUTION
- Sherawat Web Solution
- World News Update – B
- About Diamond & Diamond Jewelry – b
- Education Health Care – b
- Best Songs – B
- Rajasthan Tourism -B
- Information Technology Education – B
- Information Technology Video Education – B
- sbinfosystem – B
- Web Solution – B
-
Archives
- May 2009 (1)
- February 2009 (1)
- January 2009 (2)
- February 2008 (1)
- January 2008 (4)
- December 2007 (15)
- November 2007 (4)
-
Categories
-
RSS
Entries RSS
Comments RSS