Web solution, Websites help, Java help, C & C# Language help

Tuesday, January 8, 2008

Java Help, Java Tutorials, Java Programming, Java Tricks


Java Help, Java Tutorials, Java Programming, Java Tricks


lesson four

Working with Objects



CONTENTS

Creating New Objects

Using new

What new Does

A Note on Memory Management



Accessing and Setting Class and Instance Variables

Getting Values

Changing Values

Class Variables



Calling Methods

Class Methods



References to Objects

Casting and Converting Objects and Primitive Types

Casting Primitive Types

Casting Objects

Converting Primitive Types to Objects and Vice Versa



Odds and Ends

Comparing Objects

Determining the Class of an Object



Class and Object Reflection (Java 1.1)

The Java Class Library

Summary

Q&A




Let's start today's lesson with an obvious statement: Because Java is an
object-oriented language, you're

going to be dealing with a lot of objects. You'll create them, modify them, move
them around, change

their variables, call their methods, combine them with other objects-and, of
course, develop classes and

use your own objects in the mix.

Today, therefore, you'll learn all about the Java object in its natural habitat.
Today's topics include

Creating instances of classes

Testing and modifying class and instance variables in your new instance

Calling methods in that object

Casting (converting) objects and other data types from one class to another

Other odds and ends about working with objects

An overview of the Java class libraries




Creating New Objects

When you write a Java program, you define a set of classes. As you learned on
Day 2, "Object-Oriented

Programming and Java," classes are templates for objects; for the most part, you
merely use the class to

create instances and then work with those instances. In this section, therefore,
you'll learn how to create a

new object from any given class.

Remember strings from yesterday? You learned that using a string literal-a
series of characters enclosed in

double-quotes-creates a new instance of the class String with the value of that
string.

The String class is unusual in that respect-although it's a class, there's an
easy way to create instances of

that class using a literal. The other classes don't have that shortcut; to
create instances of those classes you

have to do so explicitly by using the new operator.

Note

What about the literals for numbers and characters? Don't they create

objects, too? Actually, they don't. The primitive data types for

numbers and characters create numbers and characters, but for

efficiency, they aren't actually objects. You can put object wrappers

around them if you need to treat them like objects (you'll learn how to

do this in "Casting and `Converting Objects and Primitive Types").

Using new

To create a new object, you use the new operator with the name of the class you
want to create an instance

of, then parentheses after that. The following examples create new instances of
the classes String,

Random, and Motorcycle, and store those new instances in variables of the
appropriate types:

String str = new String();

Random r = new Random();

Motorcycle m2 = new Motorcycle();

The parentheses are important; don't leave them off. The parentheses can be
empty (as in these examples),

in which case the most simple, basic object is created; or the parentheses can
contain arguments that

determine the initial values of instance variables or other initial qualities of
that object:

Date dt = new Date(90, 4, 1, 4, 30);

Point pt = new Point(0,0);

The number and type of arguments you can use inside the parentheses with new are
defined by the class

itself using a special method called a constructor (you'll learn more about
constructors later today). If you

try and create a new instance of a class with the wrong number or type of
arguments (or if you give it no

arguments and it needs some), then you'll get an error when you try to compile
your Java program.

Here's an example of creating several different types of objects using different
numbers and types of

arguments. The Date class, part of the java.util package, creates objects that
represent the current

date. Listing 4.1 is a Java program that shows three different ways of creating
a Date object using new.

Listing 4.1. Laura's Date program.

1: import java.util.Date;

2:

3: class CreateDates {

4:

5: public static void main(String args[]) {

6: Date d1, d2, d3;

7:

8: d1 = new Date();

9: System.out.println("Date 1: " + d1);

10:

11: d2 = new Date(71, 7, 1, 7, 30);

12: System.out.println("Date 2: " + d2);

13:

14: d3 = new Date("April 3 1993 3:24 PM");

15: System.out.println("Date 3: " + d3);

16: }

17: }

Date 1: Tue Feb 13 09:36:56 PST 1996

Date 2: Sun Aug 01 07:30:00 PDT 1971

Date 3: Sat Apr 03 15:24:00 PST 1993

Analysis

In this example, three different date objects are created using different

arguments to the class listed after new. The first instance (line 8) uses

new Date() with no arguments, which creates a Date object for

today's date (the first line of the output shows a sample; your output

will, of course, read the current date and time for you).

The second Date object you create in this example has five integer arguments.
The arguments represent a

date: year, month, day, hours, and minutes. And, as the output shows, this
creates a Date object for that

particular date: Sunday, August 1, 1971, at 7:30 a.m.

Note

Java numbers months starting from 0. So although you might expect

the seventh month to be July, month 7 in Java is indeed August.

The third version of Date takes one argument, a string, representing the date as
a text string. When the

Date object is created, that string is parsed, and a Date object with that date
and time is created (see the

third line of output). The date string can take many different formats; see the
API documentation for the

Date class (part of the java.util package) for information about what strings
you can use.

What new Does

When you use the new operator, the new instance of the given class is created,
and memory is allocated

for it. In addition (and most importantly), a special method defined in the
given class is called to initialize

the object and set up any initial values it needs. This special method is called
a constructor. Constructors

are special methods, defined in classes, that create and initialize new
instances of classes.

New Term

Constructors are special methods that initialize a new object, set its

variables, create any other objects that object needs, and generally

perform any other operations the object needs to initialize itself.

Multiple constructor definitions in a class can each have a different number or
type of arguments-then,

when you use new, you can specify different arguments in the argument list, and
the right constructor for

those arguments will be called. That's how each of those different versions of
new that you used in the

CreateDates class can create different Date objects.

When you create your own classes, you can define as many constructors as you
need to implement that

class's behavior. You'll learn how to create constructors on Day 7, "More About
Methods."

A Note on Memory Management

Memory management in Java is dynamic and automatic. When you create a new object
in Java, Java

automatically allocates the right amount of memory for that object in the heap.
You don't have to allocate

any memory for any objects explicitly; Java does it for you.

What happens when you're finished with that object? How do you de-allocate the
memory that object

uses? The answer, again, is that memory management is automatic. Once you're
done with an object, you

reassign all the variables that might hold that object and remove it from any
arrays, thereby making the

object unusable. Java has a "garbage collector" that looks for unused objects
and reclaims the memory that

those objects are using. You don't have to do any explicit freeing of memory;
you just have to make sure

you're not still holding onto an object you want to get rid of. You'll learn
more specific details about the

Java garbage collector and how it works on Day 21, "Under the Hood."

New Term

A garbage collector is a special thing built into the Java environment

that looks for unused objects. If it finds any, it automatically removes

those objects and frees the memory those objects were using.

Accessing and Setting Class and Instance Variables

Now you have your very own object, and that object may have class or instance
variables defined in it.

How do you work with those variables? Easy! Class and instance variables behave
in exactly the same

ways as the local variables you learned about yesterday; you just refer to them
slightly differently than you

do regular variables in your code.

Getting Values

To get to the value of an instance variable, you use an expression in what's
called dot notation. With dot

notation, the reference to an instance or class variable has two parts: the
object on the left side of the dot

and the variable on the right side of the dot.

New Term

Dot notation is an expression used to get at instance variables and

methods inside a given object.

For example, if you have an object assigned to the variable myObject, and that
object has a variable

called var, you refer to that variable's value like this:

myObject.var;

This form for accessing variables is an expression (it returns a value), and
both sides of the dot can also be

expressions. This means that you can nest instance variable access. If that var
instance variable itself

holds an object and that object has its own instance variable called state, you
could refer to it like this:

myObject.var.state;

Dot expressions are evaluated left to right, so you start with myObject's
variable var, which points to

another object with the variable state. You end up with the value of that state
variable after the entire

expression is done evaluating.

Changing Values

Assigning a value to that variable is equally easy-just tack an assignment
operator on the right side of the

expression:

myObject.var.state = true;

Listing 4.2 is an example of a program that tests and modifies the instance
variables in a Point object.

Point is part of the java.awt package and refers to a coordinate point with an x
and a y value.

Listing 4.2. The TestPoint Class.

1: import java.awt.Point;

2:

3: class TestPoint {

4: public static void main(String args[]) {

5: Point thePoint = new Point(10,10);

6:

7: System.out.println("X is " + thePoint.x);

8: System.out.println("Y is " + thePoint.y);

9:

10: System.out.println("Setting X to 5.");

11: thePoint.x = 5;

12: System.out.println("Setting Y to 15.");

13: thePoint.y = 15;

14:

15: System.out.println("X is " + thePoint.x);

16: System.out.println("Y is " + thePoint.y);

17:

18: }

19:}

X is 10

Y is 10

Setting X to 5.

Setting Y to 15.

X is 5

Y is 15

Analysis

In this example, you first create an instance of Point where X and Y

are both 10 (line 6). Lines 8 and 9 print out those individual values,

and you can see dot notation at work there. Lines 11 through 14

change the values of those variables to 5 and 15, respectively.

Finally, lines 16 and 17 print out the values of X and Y again to show

how they've changed.




Class Variables

Class variables, as you've already learned, are variables that are defined and
stored in the class itself. Their

values, therefore, apply to the class and to all its instances.

With instance variables, each new instance of the class gets a new copy of the
instance variables that class

defines. Each instance can then change the values of those instance variables
without affecting any other

instances. With class variables, there is only one copy of that variable. Every
instance of the class has

access to that variable, but there is only one value. Changing the value of that
variable changes it for all

the instances of that class.

You define class variables by including the static keyword before the variable
itself. You'll learn more

about this on Day 6, "Creating Classes and Applications in Java." For example,
take the following partial

class definition:

class FamilyMember {

static String surname = "Johnson";

String name;

int age;

...

}

Instances of the class FamilyMember each have their own values for name and age.
But the class

variable surname has only one value for all family members. Change surname, and
all the instances of

FamilyMember are affected.

To access class variables, you use the same dot notation as you do with instance
variables. To get or

change the value of the class variable, you can use either the instance or the
name of the class on the left

side of the dot. Both of the lines of output in this example print the same
value:

FamilyMember dad = new FamilyMember();

System.out.println("Family's surname is: " + dad.surname);

System.out.println("Family's surname is: " + FamilyMember.surname);

Because you can use an instance to change the value of a class variable, it's
easy to become confused

about class variables and where their values are coming from (remember that the
value of a class variable

affects all the instances). For this reason, it's a good idea to use the name of
the class when you refer to a

class variable-it makes your code easier to read and strange results easier to
debug.

Calling Methods

Calling a method is similar to referring to an object's instance variables:
Method calls to objects also use

dot notation. The object itself whose method you're calling is on the left side
of the dot; the name of the

method and its arguments are on the right side of the dot:

myObject.methodOne(arg1, arg2, arg3);

Note that all calls to methods must have parentheses after them, even if that
method takes no arguments:

myObject.methodNoArgs();

If the method you've called returns an object that itself has methods, you can
nest methods as you would

variables. This next example calls the getName() method, which is defined in the
object returned by the

getClass() method, which was defined in myObject. Got it?

myObject.getClass().getName();

You can combine nested method calls and instance variable references as well (in
this case you're calling

the methodTwo() method, which is defined in the object stored by the var
instance variable, which in

turn is part of the myObject object):

myObject.var.methodTwo(arg1, arg2);

System.out.println(), the method you've been using through the book this far to
print out bits of

text, is a great example of nesting variables and methods. The System class
(part of the java.lang

package) describes system-specific behavior. System.out is a class variable that
contains an instance of

the class PrintStream that points to the standard output of the system.
PrintStream instances have

a println() method that prints a string to that output stream.

Listing 4.3 shows an example of calling some methods defined in the String
class. Strings include

methods for string tests and modification, similar to what you would expect in a
string library in other

languages.

Listing 4.3. Several uses of String methods.

1: class TestString {

2:

3: public static void main(String args[]) {

4: String str = "Now is the winter of our discontent";

5:

6: System.out.println("The string is: " + str);

7: System.out.println("Length of this string: "

8: + str.length());

9: System.out.println("The character at position 5: "

10: + str.charAt(5));

11: System.out.println("The substring from 11 to 17: "

12: + str.substring(11, 17));

13: System.out.println("The index of the character d: "

14: + str.indexOf('d'));

15: System.out.print("The index of the beginning of the ");

16: System.out.println("substring \"winter\": "

17: + str.indexOf("winter"));

18: System.out.println("The string in upper case: "

19: + str.toUpperCase());

20: }

21: }

The string is: Now is the winter of our discontent

Length of this string: 35

The character at position 5: s

The substring from positions 11 to 17: winter

The index of the character d: 25

The index of the beginning of the substring "winter": 11

The string in upper case: NOW IS THE WINTER OF OUR DISCONTENT

Analysis

In line 4, you create a new instance of String by using a string

literal (it's easier that way than using new and then putting the

characters in individually). The remainder of the program simply calls

different string methods to do different operations on that string:

Line 6 prints the value of the string we created in line 4: "Now is the winter
of our

discontent".

l

Line 7 calls the length() l method in the new String object. This string has 35
characters.

Line 9 calls the charAt() method, which returns the character at the given
position in the string.

Note that string positions start at 0, so the character at position 5 is s.

l

Line 11 calls the substring() method, which takes two integers indicating a
range and returns

the substring at those starting and ending points. The substring() method can
also be called

with only one argument, which returns the substring from that position to the
end of the string.

l

Line 13 calls the indexOf() method, which returns the position of the first
instance of the given

character (here, 'd').

l

Line 15 shows a different use of the indexOf() method, which takes a string
argument and

returns the index of the beginning of that string.

l

l Finally, line 19 uses the toUpperCase() method to return a copy of the string
in all uppercase.

Class Methods

Class methods, like class variables, apply to the class as a whole and not to
its instances. Class methods

are commonly used for general utility methods that may not operate directly on
an instance of that class,

but fit with that class conceptually. For example, the String class contains a
class method called

valueOf(), which can take one of many different types of arguments (integers,
booleans, other objects,

and so on). The valueOf() method then returns a new instance of String
containing the string value

of the argument it was given. This method doesn't operate directly on an
existing instance of String, but

getting a string from another object or data type is definitely a String-like
operation, and it makes sense

to define it in the String class.

Class methods can also be useful for gathering general methods together in one
place (the class). For

example, the Math class, defined in the java.lang package, contains a large set
of mathematical

operations as class methods-there are no instances of the class Math, but you
can still use its methods

with numeric or boolean arguments. For example, the class method Math.max()
takes two arguments

and returns the larger of the two. You don't need to create a new instance of
Math; just call the method

anywhere you need it, like this:

in biggerOne = Math.max(x, y);

To call a class method, you use dot notation as you do with instance methods. As
with class variables, you

can use either an instance of the class or the class itself on the left site of
the dot. However, for the same

reasons noted in the discussion on class variables, using the name of the class
for class methods makes

your code easier to read. The last two lines in this example produce the same
result (the string "5"):

String s, s2;

s = "foo";

s2 = s.valueOf(5);

s2 = String.valueOf(5);

References to Objects

As you work with objects, one important thing going on behind the scenes is the
use of references to those

objects. When you assign objects to variables, or pass objects as arguments to
methods, you are passing

references to those objects, not the objects themselves or copies of those
objects.

An example should make this clearer. Examine Listing 4.4, which shows a simple
example of how

references work.

Listing 4.4. A references example.

1: import java.awt.Point;

2:

3: class ReferencesTest {

4: public static void main (String args[]) {

5: Point pt1, pt2;

6: pt1 = new Point(100, 100);

7: pt2 = pt1;

8:

9: pt1.x = 200;

10: pt1.y = 200;

11: System.out.println("Point1: " + pt1.x + ", " + pt1.y);

12: System.out.println("Point2: " + pt2.x + ", " + pt2.y);

13: }

14: }

Point1: 200, 200

Point2: 200, 200

Analysis

In the first part of this program, you declare two variables of type

Point (line 5), create a new Point object to pt1 (line 6), and

finally, assign the value of pt1 to pt2 (line 7).

Now, here's the challenge. After changing pt1's x and y instance variables in
lines 9 and 10, what will

pt2 look like?

As you can see, pt2's x and y instance variables were also changed, even though
you never explicitly

changed them. When you assign the value of pt1 to pt2, you actually create a
reference from pt2 to the

same object to which pt1 refers (see Figure 4.1). Change the object that pt2
refers to, and you also

change the object that pt1 points to, because both are references to the same
object.

Figure 4.1 : References to objects.

Note

If you actually do want pt1 and pt2 to point to separate objects, you

should use new Point() for both lines to create separate objects.

The fact that Java uses references becomes particularly important when you pass
arguments to methods.

You'll learn more about this later today, but keep these references in mind.

Technical Note

There are no explicit pointers or pointer arithmetic in Java as there are

in C-like languages-just references. However, with these references,

and with Java arrays, you have most of the capabilities that you have

with pointers without the confusion and lurking bugs that explicit

pointers can create.

Casting and Converting Objects and Primitive

Types

Sometimes in your Java programs you may have a value stored somewhere that is
the wrong type for what

you want to do with it. Maybe it's an instance of the wrong class, or perhaps
it's a float and you want it

to be an int. To convert the value of one type to another, you use casting.
Casting is a programming term

that means, effectively, converting a value or an object from one type to
another. The result of a cast is a

new value or object; casting does not change the original object or value.

New Time

Casting converts the value of an object or primitive type into another

type.

Although the concept of casting is a simple one, the rules for what types in
Java can be converted to what

other types are complicated by the fact that Java has both primitive types (int,
float, boolean), and

object types (String, Point, Window, and so on). There are three forms of casts
and conversions to

talk about in this section:

Casting between primitive types: int to float or float l to double

l Casting between object types: an instance of a class to an instance of another
class

l Converting primitive types to objects and then extracting primitive values
back out of those objects

Casting Primitive Types

Casting between primitive types allows you to "convert" the value of one type to
another primitive

type-for example, to assign a number of one type to a variable of another type.
Casting between primitive

types most commonly occurs with the numeric types; boolean values cannot be cast
to any other primitive

type.

Often, if the type you are casting to is "larger" than the type of the value
you're converting, you may not

have to use an explicit cast. You can often automatically treat a byte or a
character as an int, for

example, or an int as a long, an int as a float, or anything as a double
automatically. In most

cases, because the larger type provides more precision than the smaller, no loss
of information occurs

when the value is cast. The exception is casting integers to floating-point
values; casting an int or a

long to a float or a long to a double may cause some loss of precision.

To convert a large value to smaller type, you must use an explicit cast, because
converting that value may

result in a loss of precision. Explicit casts look like this:

(typename)value

In this form, typename is the name of the type you're converting to (for
example: short, int, float,

boolean), and value is an expression that results in the value you want to
convert. So, for example, in

this expression the value of x is divided by the value of y and the result is
cast to an int:

(int) (x / y);

Note that because the precedence of casting is higher than that of arithmetic,
you have to use parentheses

here; otherwise, the value of x would be cast first and then divided by y (which
might very well be a very

different result).

Casting Objects

Instances of classes can also be cast to instances of other classes, with one
restriction: The class of the

object you're casting and the class you're casting it to must be related by
inheritance; that is, you can cast

an object only to an instance of its class's sub- or superclass-not to any
random class.

Analogous to converting a primitive value to a larger type, some objects may not
need to be cast

explicitly. In particular, because subclasses contain all the same information
as their superclass, you can

use an instance of a subclass anywhere a superclass is expected. (Did you just
have to read that sentence

four times before you understood it? I had to rewrite it a whole lot of times
before it became even that

simple. Bear with me, its not that bad. Let's try an example.) Suppose you have
a method that takes two

arguments: one of type Object, and one of type Number. You don't have to pass
instances of those

particular classes to that method. For the Object argument, you can pass any
subclass of Object (any

object, in other words), and for the Number argument you can pass in any
instance of any subclass of

Number (Integer, Boolean, Float, and so on); you don't have to explicitly
convert them first.

Casting downward in the class hierarchy is automatic, but casting upward is not.
Converting an instance of

a subclass to an instance of a superclass loses the information the original
subclass provided and requires

an explicit cast. To cast an object to another class, you use the same casting
operation that you used for

base types:

(classname)object

In this case, classname is the name of the class you want to cast the object to,
and object is a

reference to the object you're casting. Note that casting creates a reference to
the old object of the type

classname; the old object still continues to exist as it did before.

Here's a (fictitious) example of a cast of an instance of the class GreenApple
to an instance of the class

Apple (where GreenApple is theoretically a subclass of Apple with more
information to define the

apple as green):

GreenApple a;

Apple a2;

a = new GreenApple();

a2 = (Apple) a;

In addition to casting objects to classes, you can also cast objects to
interfaces-but only if that object's

class or one of its superclasses actually implements that interface. Casting an
object to an interface means

that you can call one of that interface's methods even if that object's class
does not actually implement that

interface. You'll learn more about interfaces in Week 3.

Converting Primitive Types to Objects and Vice Versa

Now you know how to cast a primitive type to another primitive type and how to
cast between classes.

How can you cast one to the other?

You can't! Primitive types and objects are very different things in Java and you
can't automatically cast or

convert between the two. However, the java.lang package includes several special
classes that

correspond to each primitive data type: Integer for ints, Float for floats,
Boolean for

booleans, and so on. Note that the class names have an initial capital letter,
and the primitive types are

lowercase. Java treats these names very differently, so don't confuse them, or
your methods and variables

won't behave the way you expect.

Using class methods defined in these classes, you can create an
object-equivalent for all the primitive

types using new. The following line of code creates an instance of the Integer
class with the value 35:

Integer intObject = new Integer(35);

Once you have actual objects, you can treat those values as objects. Then, when
you want the primitive

values back again, there are methods for that as well-for example, the intValue()
method extracts an

int primitive value from an Integer object:

int theInt = intObject.intValue(); // returns 35

See the Java API documentation for these special classes for specifics on the
methods for converting

primitives to and from objects.

Note

In Java 1.0 there are special type classes for Boolean,

Character, Double, Float, Integer, and Long. Java 1.1

adds classes for Byte and Short, as well as a special wrapper class

for Void. The latter classes are used primarily for object reflection.

Odds and Ends

This section is a catchall for other information about working with objects,
particularly the following:

l Comparing objects

l Finding out the class of any given object

l Testing to see whether an object is an instance of a given class

Comparing Objects

Yesterday you learned about operators for comparing values: equals, not equals,
less than, and so on. Most

of these operators work only on primitive types, not on objects. If you try to
use other values as operands,

the Java compiler produces errors.

The exception to this rule is with the operators for equality: == (equal) and !=
(not equal). These

operators, when used with objects, test whether the two operands refer to
exactly the same object in

memory.

What should you do if you want to be able to compare instances of your class and
have meaningful

results? You have to implement special methods in your class, and you have to
call those methods using

those method names.

Technical Note

Java does not have the concept of operator overloading-that is, the

ability to redefine the behavior of the built-in operators using methods

in your own classes. The built-in operators remain defined only for

numbers.

A good example of this is the String class. It is possible to have two strings,
two independent objects in

memory with the same values-that is, the same characters in the same order.
According to the == operator,

however, those two String objects will not be equal, because, although their
contents are the same, they

are not the same object.

The String class, therefore, defines a method called equals() that tests each
character in the string

and returns true if the two strings have the same values. Listing 4.5
illustrates this.

Listing 4.5. A test of string equality.

1: class EqualsTest {

2: public static void main(String args[]) {

3: String str1, str2;

4: str1 = "she sells sea shells by the sea shore.";

5: str2 = str1;

6:

7: System.out.println("String1: " + str1);

8: System.out.println("String2: " + str2);

9: System.out.println("Same object? " + (str1 == str2));

10:

11: str2 = new String(str1);

12:

13: System.out.println("String1: " + str1);

14: System.out.println("String2: " + str2);

15: System.out.println("Same object? " + (str1 == str2));

16: System.out.println("Same value? " + str1.equals(str2));

17: }

18: }

String1: she sells sea shells by the sea shore.

String2: she sells sea shells by the sea shore.

Same object? true

String1: she sells sea shells by the sea shore.

String2: she sells sea shells by the sea shore.

Same object? false

Same value? true

Analysis

The first part of this program (lines 4 through 6) declares two

variables (str1 and str2) assigns the literal she sells sea

shells by the sea shore. to str1, and then assigns that

value to str2. As you learned earlier when we talked about object

references, now str1 and str2 point to the same object, and the

equality test at line 10 proves that.

In the second part, you create a new string object with the same value as str1
and assign str2 to that

new string object. Now you have two different string objects in str1 and str2,
both with the same

value. Testing them to see whether they're the same object by using the ==
operator (line 16) returns the

expected answer (false-they are not the same object in memory), as does testing
them using the

equals() method (line 17) (true-they have the same values).

Technical Note

Why can't you just use another literal when you change str2, rather

than using new? String literals are optimized in Java-if you create a

string using a literal, and then use another literal with the same

characters, Java knows enough to give you the first String object

back. Both strings are the same objects-to create two separate objects

you have to go out of your way.

Determining the Class of an Object

Want to find out the class of an object? Here's the way to do it for an object
assigned to the variable obj:

String name = obj.getClass().getName();

What does this do? The getClass() method is defined in the Object class, and as
such is available

for all objects. The result of that method is a Class object (where Class is
itself a class), which has a

method called getName(). getName() returns a string representing the name of the
class.

Another test that might be useful to you is the instanceof operator. instanceof
has two operands:

an object on the left and the name of a class on the right. The expression
returns true or false based on

whether the object is an instance of the named class or any of that class's
subclasses:

"foo" instanceof String // true

Point pt = new Point(10, 10);

pt instanceof String // false

The instanceof operator can also be used for interfaces; if an object implements
an interface, the

instanceof operator with that interface name on the right side returns true.
You'll learn all about

interfaces in Week 3.

Class and Object Reflection (Java 1.1)

Reflection, also known as introspection, is a somewhat lofty term to describe
the ability to "look inside" a

class or an object and get information about that object's variables and methods
as well as actually set and

get the values of those variables and to call methods. Object reflection is
useful for tools such as class

browsers or debuggers, where getting at the information of an object on-the-fly
allows you to explore what

that object can do, or for component-based programs such as Java Beans, where
the ability for one object

to query another object about what it can do (and then ask it to do something)
is useful to building larger

applications.

The classes that support reflection of Java classes and objects will be part of
the core Java 1.1 API (they

are not available in the 1.0.2 version of the JDK). A new package,
java.lang.reflect, will contain

new classes to support reflection, which include the following:

l Field, for managing and finding out information about class and instance
variables

l Method, for managing class and instance methods

Constructor, for managing the special methods for creating new instances of
classes (you'll

learn more about constructors on Day 7)

l

l Array, for managing arrays

Modifier, for decoding modifier information about classes, variables and methods
(more about

modifiers on Day 15, "Modifiers, Access Control, and Class Design")

l

In addition, there will be a number of new methods available in the Class class
to help tie together the

various reflection classes.

You can find out more about the new reflection classes and methods from

http://java.sun.com/products/JDK/1.1/designspecs/reflection/.

The Java Class Library

To finish up today, let's look at the Java class library. Actually, you've had
some experience with some of

the Java classes already, so they shouldn't seem that strange.

The Java class library provides the set of classes that are guaranteed to be
available in any commercial

Java environment (for example, in any Java development environment or in
browsers such as Netscape).

Those classes are in the java package and include all the classes you've seen so
far in this book, plus a

whole lot more classes you'll learn about later on in this book (and more you
may not learn about at all).

The Java Developer's Kit comes with documentation for all of the Java class
library, which includes

descriptions of each class's instance variables, methods, constructors,
interfaces, and so on. You can get to

this documentation (called the Java Application Programmer's Interface, or API)
via the Web at

http://java.sun.com:80/products/JDK/CurrentRelease/api/packages.html. A

shorter summary of the Java API is in appendix C as well. Exploring the Java
class library and its methods

and instance variables is a great way to figure out what Java can and cannot do,
as well as how it can

become a starting point for your own development.

Here are the class packages that are part of the Java class library:

java.lang-Classes that apply to the language itself, including the Object class,
the String

class, and the System class. It also contains the special classes for the
primitive types (Integer,

Character, Float, and so on). You'll get at least a glance at most of the
classes in this package

in this first week.

l

java.util-Utility classes, such as Date, as well as simple collection classes,
such as Vector

and Hashtable. You'll learn more about these classes in the Bonus Week.

l

java.io-Input and output classes for writing to and reading from streams (such
as standard input

and output) and for handling files. Day 19, "Streams and I/O," describes the
classes in this package.

l

java.net-Classes for networking support, including Socket and URL (a class to
represent

references to documents on the World Wide Web). You'll learn a little about
networking on Day 14,

"Windows, Networking, and Other Tidbits," and then on Day 26, "Client/Server
Networking in

Java."

l

java.awt-This is the Abstract Windowing Toolkit. It contains classes to
implement graphical

user interface features, including classes for Window, Menu, Button, Font,
CheckBox, and so

on. It also includes mechanisms for managing system events and for processing
images (in the

java.awt.Image package). You'll learn all about the awt in Week 2.

l

l java.applet-Classes to implement Java applets.

In addition to the Java classes, your development environment may also include
additional classes that

provide other utilities or functionality. Although these classes may be useful,
because they are not part of

the standard Java library, they may not be available to other people trying to
run your Java program unless

you explicitly include those classes with your program. This is particularly
important for applets, because

applets are expected to be able to run on any platform, using any Java-enabled
browser. Only classes

inside the java package are guaranteed to be available on all browsers and Java
environments.

Summary

Objects, objects everywhere. Today, you've learned all about how to deal with
objects: how to create

them, how to find out and change the values of their variables, and how to call
their methods. You have

also learned how to copy and compare them and how to convert them into other
objects. Finally, you have

learned a bit about the Java class libraries-which give you a whole slew of
classes to play with in your

own programs.

You now have the fundamentals of how to deal with most simple things in the Java
language. All you

have left are arrays, conditionals, and loops, which you'll learn about
tomorrow. Then you'll learn how to

define and use classes in Java applications on Day 6, and launch directly into
applets next week. With just

about everything you do in your Java programs, you'll always come back to
objects.




Q&A

Q: I'm confused about the differences between objects and the primitive data
types, such as

int and boolean.

A: The primitive types in the language (byte, short, int, long, float, double,
boolean,

and char) represent the smallest things in the language. They are not objects,
although in many

ways they can be handled like objects-they can be assigned to variables and
passed in and out of

methods. Most of the operations that work exclusively on objects, however, will
not work with

primitive types.

Objects are instances of classes and, as such, are usually much more complex
data types than

simple numbers and characters, often containing numbers and characters as
instance or class

variables.

Q: No pointers in Java? If you don't have pointers, how are you supposed to do
something like

linked lists, where you have a pointer from one nose to another so you can
traverse them?

A: Java doesn't have no pointers at all; it has no explicit pointers. Object
references are, effectively,

pointers. So to create something like a linked list, you would create a class
called Node, which

would have an instance variable also of type Node. Then to link together node
objects all you

need to do is assign a node object to the instance variable of the object just
before it in the list.

Because object references are pointers, linked lists set up this way will behave
as you would

expect them to.

Q: In the section on calling methods, you had examples of calling a method with
a different

number of arguments each time-and it gave a different kind of result. How is
that possible?

A: That's called method overloading. Overloading means that the same method can
have different

behavior based on the arguments it's called with-and the number and type of
arguments can vary.

When you define methods in your own classes, you define separate method
signatures with

different sets of arguments and different definitions. When a method is called,
Java figures out

which definition to execute based on the number and type of arguments with which
you called it.

You'll learn all about this on Day 6.

Q: No operator overloading in Java? Why not? I thought Java was based on C++,
and C++ has

operator overloading.

A: Java was indeed based on C++, but it was also designed to be simple, so many
of C++'s features

have been removed. The argument against operator overloading is that because the
operator can

be defined to mean anything; it makes it very difficult to figure out what any
given operator is

doing at any one time. This can result in entirely unreadable code. When you use
a method, you

know it can mean many things to many classes, but when you use an operator you
would like to

know that it always means the same thing. Given the potential for abuse, the
designers of Java felt

it was one of the C++ features that was best left out.

Java Help, Java Tutorials, Java Programming, Java Tricks



Java Help, Java Tutorials, Java Programming, Java Tricks

Lesson Three

Java Basics






CONTENTS



Statements and Expressions



Variables and Data Types

Declaring Variables

Notes on Variable Names

Variable Types

Assigning Values to Variables



Comments



Literals

Number Literals

Boolean Literals

Character Literals

String Literals



Expressions and Operators

Arithmetic

More About Assignment

Incrementing and Decrementing

Comparisons

Logical Operators

Bitwise Operators

Operator Precedence



String Arithmetic

Summary

Q&A



Already this week you've learned about Java programming in very broad terms-what
a Java program andan executable look like, and how to create simple classes. For
the remainder of this week, you're going to get down to details and deal with
the specifics of what the Java language looks like.

Today you won't define any classes or objects or worry about how any of them
communicate inside a

Java program. Rather, you'll draw closer and examine simple Java statements-the
basic things you can do

in Java within a method definition such as main().

Today you'll learn about the following:

Java statements and expressions

Variables and data types

Comments

Literals

Arithmetic

Comparisons

Logical operators

Technical Note

Java looks a lot like C++, and-by extension-like C. Much of the

syntax will be very familiar to you if you are used to working in these

languages. If you are an experienced C or C++ programmer, you may

want to pay special attention to the technical notes (such as this one),

because they provide information about the specific differences

between these and other traditional languages and Java.

Statements and Expressions

A statement indicates the simplest tasks you can accomplish in Java; a statement
forms a single Java

operation. All the following are simple Java statements:

int i = 1;

import java.awt.Font;

System.out.println("This motorcycle is a "

+ color + " " + make);

m.engineState = true;

Statements sometimes return values-for example, when you add two numbers
together or test to see

whether one value is equal to another. These kind of statements are called
expressions. You'll learn about

these later today.



White space in Java statements, as with C, is unimportant. A statement can be
contained on a single line

or on multiple lines, and the Java compiler will be able to read it just fine.
The most important thing to

remember about Java statements is that each one ends with a semicolon (;).
Forget the semicolon, and

your Java program won't compile.

Java also has compound statements, or blocks, which can be placed wherever a
single statement can.

Block statements are surrounded by braces ({}). You'll learn more about blocks
on Day 5, "Arrays,

Conditionals, and Loops."



Variables and Data Types

Variables are locations in memory in which values can be stored. Each one has a
name, a type, and a

value. Before you can use a variable, you have to declare it. After it is
declared, you can then assign

values to it (you can also declare and assign a value to a variable at the same
time, as you'll learn in this

section).



Java actually has three kinds of variables: instance variables, class variables,
and local variables.

Instance variables, as you learned yesterday, are used to define the attributes
of a particular object. Class

variables are similar to instance variables, except their values apply to all
that class's instances (and to the

class itself) rather than having different values for each object.

Local variables are declared and used inside method definitions, for example,
for index counters in loops,

as temporary variables, or to hold values that you need only inside the method
definition itself. They can

also be used inside blocks, which you'll learn about on Day 5. Once the method
(or block) finishes

executing, the variable definition and its value cease to exist. Use local
variables to store information

needed by a single method and instance variables to store information needed by
multiple methods in the

object.



Although all three kinds of variables are declared in much the same ways, class
and instance variables

are accessed and assigned in slightly different ways from local variables. Today
you'll focus on variables

as used within method definitions; tomorrow you'll learn how to deal with
instance and class variables.

Note Unlike other languages, Java does not have global variables-that is,

variables that are global to all parts of a program. Instance and class

variables can be used to communicate global information between

and among objects. Remember that Java is an object-oriented

language, so you should think in terms of objects and how they

interact, rather than in terms of programs.

Declaring Variables

To use any variable in a Java program, you must first declare it. Variable
declarations consist of a type

and a variable name:

int myAge;

String myName;

boolean isTired;

Variable definitions can go anywhere in a method definition (that is, anywhere a
regular Java statement

can go), although they are most commonly declared at the beginning of the
definition before they are

used:

public static void main (String args[]) {

int count;

String title;

boolean isAsleep;

...

}

You can string together variable names with the same type on one line:

int x, y, z;

String firstName, LastName;

You can also give each variable an initial value when you declare it:

int myAge, mySize, numShoes = 28;

String myName = "Laura";

boolean isTired = true;

int a = 4, b = 5, c = 6;

If there are multiple variables on the same line with only one initializer (as
in the first of the previous

examples), the initial value applies to only the last variable in a declaration.
You can also group

individual variables and initializers on the same line using commas, as with the
last example.

Local variables must be given values before they can be used (your Java program
will not compile if you

try to use an unassigned local variable). For this reason, it's a good idea
always to give local variables

initial values. Instance and class variable definitions do not have this
restriction. (Their initial value

depends on the type of the variable: null for instances of classes, 0 for
numeric variables, '\0' for

characters, and false for booleans.)

Notes on Variable Names

Variable names in Java can start with a letter, an underscore (_), or a dollar
sign ($). They cannot start

with a number. After the first character, your variable names can include any
letter or number. Symbols,

such as %, *, @, and so on, are often reserved for operators in Java, so be
careful when using symbols in

variable names.

In addition, the Java language uses the Unicode character set. Unicode is a
character set definition that

not only offers characters in the standard ASCII character set, but also
includes several thousand other

characters for representing most international alphabets. This means that you
can use accented characters

and other glyphs as legal characters in variable names, as long as they have a
Unicode character number

above 00C0.

Warning

The Unicode specification is a two-volume set of lists of thousands of

characters. If you don't understand Unicode, or don't think you have a

use for it, it's safest just to use plain numbers and letters in your

variable names. You'll learn a little more about Unicode later.

Finally, note that the Java language is case sensitive, which means that
uppercase letters are different

from lowercase letters. This means that the variable X is different from the
variable x, and a rose is not

a Rose is not a ROSE. Keep this in mind as you write your own Java programs and
as you read Java

code other people have written.

By convention, Java variables have meaningful names, often made up of several
words combined. The

first word is lowercase, but all following words have an initial uppercase
letter:

Button theButton;

long reallyBigNumber;

boolean currentWeatherStateOfPlanetXShortVersion;

Variable Types

In addition to the variable name, each variable declaration must have a type,
which defines what values

that variable can hold. The variable type can be one of three things:

One of the eight primitive data types

The name of a class or interface

An array

You'll learn about how to declare and use array variables on Day 5; this lesson
focuses on the primitive

and class types.

Primitive Types

The eight primitive data types handle common types for integers, floating-point
numbers, characters, and

boolean values (true or false). They're called primitive because they're built
into the system and are

not actual objects, which makes them more efficient to use. Note that these data
types are

machine-independent, which means that you can rely on their sizes and
characteristics to be consistent

across your Java programs.

There are four Java integer types, each with a different range of values (as
listed in Table 3.1). All are

signed, which means they can hold either positive or negative numbers. Which
type you choose for your

variables depends on the range of values you expect that variable to hold; if a
value becomes too big for

the variable type, it is silently truncated.

Table 3.1. Integer types.

Type Size Range

byte 8 bits -128 to 127

short 16 bits -32,768 to 32,767

int 32 bits -2,147,483,648 to 2,147,483,647

long 64 bits -9,223,372,036,854,775,808 to

9,223,372,036,854,775,807

Floating-point numbers are used for numbers with a decimal part. Java
floating-point numbers are

compliant with IEEE 754 (an international standard for defining floating-point
numbers and arithmetic).

There are two floating-point types: float (32 bits, single precision) and double
(64 bits, double

precision).

The char type is used for individual characters. Because Java uses the Unicode
character set, the char

type has 16 bits of precision, unsigned.

Finally, the boolean type can have one of two values, true or false. Note that
unlike in other C-like

languages, boolean is not a number, nor can it be treated as one. All tests of
boolean variables should

test for true or false.

Note that all the primitive types are in lowercase. Be careful when you use them
in your programs that

you do use the lowercase, because there are also classes with the same names
(and an initial capital

letter) that have different behavior-so, for example, the primitive type boolean
is different from the

Boolean class. You'll learn more about these special classes and what they're
used for on Day 4,

"Working with Objects."

Class Types

In addition to the eight primitive data types, variables in Java can also be
declared to hold an instance of

a particular class:

String LastName;

Font basicFont;



OvalShape myOval;



Each of these variables can hold instances of the named class or of any of its
subclasses. The latter is

useful when you want a variable to be able to hold different instances of
related classes. For example,

let's say you had a set of fruit classes-Apple, Pear, Strawberry, and so on- all
of which inherited

from the general class Fruit. By declaring a variable of type Fruit, that
variable can then hold

instances of any of the Fruit classes. Declaring a variable of type Object means
that variable can

hold any object.



Technical Note

Java does not have a typedef statement (as in C and C++). To

declare new types in Java, you declare a new class; then variables can

be declared to be of that class's type.

Assigning Values to Variables

Once a variable has been declared, you can assign a value to that variable by
using the assignment

operator =, like this:

size = 14;

tooMuchCaffiene = true;



Comments

Java has three kinds of comments: two for regular comments in source code and
one for the special

documentation system javadoc.

The symbols /* and */ surround multiline comments, as in C or C++. All text
between the two

delimiters is ignored:

/* I don't know how I wrote this next part; I was working

really late one night and it just sort of appeared. I

suspect the code elves did it for me. It might be wise

not to try and change it.

*/

These comments cannot be nested; that is, you cannot have a comment inside a
comment.

Double-slashes (//) can be used for a single line of comment. All the text up to
the end of the line is

ignored:

int vices = 7; // are there really only 7 vices?

The final type of comment begins with /** and ends with */. The contents of
these special comments

are used by the javadoc system, but are otherwise used identically to the first
type of comment.

javadoc is used to generate API documentation from the code. You'll learn more
about javadoc on

Day 22, "Java Programming Tools."

Literals

Literal is a programming language term that essentially means that what you type
is what you get. For

example, if you type 4 in a Java program, you automatically get an integer with
the value 4. If you type

'a', you get a character with the value a. Literals are used to indicate simple
values in your Java

programs.



New Term

A literal is a simple value where "what you type is what you get."

Numbers, characters, and strings are all examples of literals.

Literals may seem intuitive most of the time, but there are some special cases
of literals in Java for

different kinds of numbers, characters, strings, and boolean values.

Number Literals

There are several integer literals. 4, for example, is a decimal integer literal
of type int (although you

can assign it to a variable of type byte or short because it's small enough to
fit into those types). A

decimal integer literal larger than an int is automatically of type long. You
also can force a smaller

number to a long by appending an L or l to that number (for example, 4L is a
long integer of value

4). Negative integers are preceded by a minus sign-for example, -45.

Integers can also be expressed as octal or hexadecimal: A leading 0 indicates
that a number is octal-for

example, 0777 or 0004. A leading 0x (or 0X) means that it is in hex (0xFF,
0XAf45). Hexadecimal

numbers can contain regular digits (0-9) or upper- or lowercase hex digits (a-f
or A-F).

Floating-point literals usually have two parts, the integer part and the decimal
part-for example,

5.77777. A floating-point literal results in a floating-point number of type
double, regardless of the

precision of the number. You can force the number to the type float by appending
the letter f (or F) to

that number-for example, 2.56F.

You can use exponents in floating-point literals using the letter e or E
followed by the exponent (which

can be a negative number): 10e45 or .36E-2.

Boolean Literals

Boolean literals consist of the keywords true and false. These keywords can be
used anywhere you

need a test or as the only possible values for boolean variables.

Character Literals

Character literals are expressed by a single character surrounded by single
quotes: 'a', '#', '3', and

so on. Characters are stored as 16-bit Unicode characters. Table 3.2 lists the
special codes that can

represent nonprintable characters, as well as characters from the Unicode
character set. The letter d in the

octal, hex, and Unicode escapes represents a number or a hexadecimal digit (a-f
or A-F).

Table 3.2. Character escape codes.

Escape Meaning

\n Newline

\t Tab

\b Backspace

\r Carriage return

\f Formfeed

\\ Backslash

\' Single quote

\" Double quote

\ddd Octal

\xdd Hexadecimal

\udddd Unicode character

Technical Note

C and C++ programmers should note that Java does not include

character codes for \a (bell) or \v (vertical tab).

String Literals

A combination of characters is a string. Strings in Java are instances of the
class String. Strings are not

simply arrays of characters as they are in C or C++, although they do have many
array-like

characteristics (for example, you can test their length, and access and change
individual characters).

Because string objects are real objects in Java, they have methods that enable
you to combine, test, and

modify strings very easily.

String literals consist of a series of characters inside double quotes:

"Hi, I'm a string literal."

"" //an empty string

Strings can contain character constants such as newline, tab, and Unicode
characters:

"A string with a \t tab in it"

"Nested strings are \"strings inside of\" other strings"

"This string brought to you by Java\u2122"

In the last example, the Unicode code sequence for \u2122 produces a trademark
symbol ( ).

Note

Just because you can represent a character using a Unicode escape

does not mean your computer can display that character-the computer

or operating system you are running may not support Unicode, or the

font you're using may not have a glyph (picture) for that character.

All that Unicode escapes in Java provide is a way to encode Unicode

characters for systems that support Unicode.

Java 1.1 will provide better capabilities for the display of Unicode

characters and for handling international character sets.

When you use a string literal in your Java program, Java automatically creates
an instance of the class

String for you with the value you give it. Strings are unusual in this respect;
the other literals do not

behave in this way (none of the primitive data types are actual objects), and
usually creating a new object

involves explicitly creating a new instance of a class. You'll learn more about
strings, the String class,

and the things you can do with strings later today and tomorrow.

Expressions and Operators

Expressions are the simplest form of statement in Java that actually
accomplishes something: All

expressions, when evaluated, return a value (other statements don't necessarily
do so). Arithmetic and

tests for equality and magnitude are common examples of expressions. Because
they return a value, you

can assign that result to a variable or test that value in other Java
statements.

Most of the expressions in Java use operators. Operators are special symbols for
things like arithmetic,

various forms of assignment, increment and decrement, and logical operations.

New Term

Expressions are statements that return a value.

New Term

Operators are special symbols that are commonly used in expressions.

Arithmetic

Java has five operators for basic arithmetic (see Table 3.3).

Table 3.3. Arithmetic operators.

Operator Meaning Example

+ Addition 3 + 4

- Subtraction 5 - 7

* Multiplication 5 * 5

/ Division 14 / 7

% Modulus 20 % 7

Each operator takes two operands, one on either side of the operator. The
subtraction operator (-) can

also be used to negate a single operand.

Integer division results in an integer. Because integers don't have decimal
fractions, any remainder is

ignored. The expression 31 / 9, for example, results in 3 (9 goes into 31 only 3
times).

Modulus (%) gives the remainder once the operands have been evenly divided. For
example, 31 % 9

results in 4 because 9 goes into 31 three times, with 4 left over.

Note that the result type of most arithmetic operations involving integers is an
int regardless of the

original type of the operands (shorts and bytes are both automatically converted
to int). If either or

both operands is of type long, the result is of type long. If one operand is an
integer and another is a

floating-point number, the result is a floating point. (If you're interested in
the details of how Java

promotes and converts numeric types from one type to another, you may want to
check out the Java

Language Specification on Sun's official Java Web site at http://java.sun.com/;
that's more

detail than I want to cover here.)

Listing 3.1 is an example of simple arithmetic in Java.

Listing 3.1. Simple arithmetic.

1: class ArithmeticTest {

2: public static void main (String args[]) {

3: short x = 6;

4: int y = 4;

5: float a = 12.5f;

6: float b = 7f;

7:

8: System.out.println("x is " + x + ", y is " + y);

9: System.out.println("x + y = " + (x + y));

10: System.out.println("x - y = " + (x - y));

11: System.out.println("x / y = " + (x / y));

12: System.out.println("x % y = " + (x % y));

13:

14: System.out.println("a is " + a + ", b is " + b);

15: System.out.println("a / b = " + (a / b));

16: }

17: }

x is 6, y is 4

x + y = 10

x - y = 2

x / y = 1

x % y = 2

a is 12.5, b is 7

a / b = 1.78571



Analysis

In this simple Java application (note the main() method), you

initially define four variables in lines 3 through 6: x and y, which are

integers (type int), and a and b, which are floating-point numbers

(type float). Keep in mind that the default type for floating-point

literals (such as 12.5) is double, so to make sure these are

numbers of type float, you have to use an f after each one (lines 5

and 6).

The remainder of the program merely does some math with integers and
floating-point numbers and

prints out the results.

There is one other thing to mention about this program: the method
System.out.println().

You've seen this method on previous days, but you haven't really learned exactly
what it does. The

System.out.println() method merely prints a message to the standard output of
your system-to

the screen, to a special window, or maybe just to a special log file, depending
on your system and the

development environment you're running. The System.out.println() method takes a
single

argument-a string-but you can use + to concatenate multiple values into a single
string, as you'll learn

later today.

More About Assignment

Variable assignment is a form of expression; in fact, because one assignment
expression results in a

value, you can string them together like this:

x = y = z = 0;

In this example, all three variables now have the value 0.

The right side of an assignment expression is always evaluated before the
assignment takes place. This

means that expressions such as x = x + 2 do the right thing; 2 is added to the
value of x, and then

that new value is reassigned to x. In fact, this sort of operation is so common
that Java has several

operators to do a shorthand version of this, borrowed from C and C++. Table 3.4
shows these shorthand

assignment operators.

Table 3.4. Assignment operators.

Expression Meaning

x += y x = x + y

x -= y x = x - y

x *= y x = x * y

x /= y x = x / y

Technical Note

Technically, the shorthand assignment and longhand expressions are

not exactly equivalent, particularly in cases where x or y may

themselves be complicated expressions and your code relies on side

effects of those expressions. In most instances, however, they are

functionally equivalent. For more information about very complicated

expressions, evaluation order, and side effects, you may want to

consult the Java Language Specification.

Incrementing and Decrementing

As in C and C++, the ++ and -- operators are used to increment or decrement a
variable's value by 1.

For example, x++ increments the value of x by 1 just as if you had used the
expression x = x + 1.

Similarly x-- decrements the value of x by 1. (Unlike C and C++, Java allows x
to be floating point.)

These increment and decrement operators can be prefixed or postfixed; that is,
the ++ or -- can appear

before or after the value it increments or decrements. For simple increment or
decrement expressions,

which one you use isn't overly important. In complex assignments, where you are
assigning the result of

an increment or decrement expression, which one you use makes a difference.

Take, for example, the following two expressions:

y = x++;

y = ++x;

These two expressions yield very different results because of the difference
between prefix and postfix.

When you use postfix operators (x++ or x--), y gets the value of x before x is
changed; using prefix,

the value of x is assigned to y after the change has occurred. Listing 3.2 is a
Java example of how all this

works.

Listing 3.2. Test of prefix and postfix increment operators.

1: class PrePostFixTest {

2:

3: public static void main (String args[]) {

4: int x = 0;

5: int y = 0;

6:

7: System.out.println("x and y are " + x + " and " + y );

8: x++;

9: System.out.println("x++ results in " + x);

10: ++x;

11: System.out.println("++x results in " + x);

12: System.out.println("Resetting x back to 0.");

13: x = 0;

14: System.out.println("------------");

15: y = x++;

16: System.out.println("y = x++ (postfix) results in:");

17: System.out.println("x is " + x);

18: System.out.println("y is " + y);

19: System.out.println("------------");

20:

21: y = ++x;

22: System.out.println("y = ++x (prefix) results in:");

23: System.out.println("x is " + x);

24: System.out.println("y is " + y);

25: System.out.println("------------");

26:

27: }

28: }

x and y are 0 and 0

x++ results in 1

++x results in 2

Resetting x back to 0.

------------

y = x++ (postfix) results in:

x is 1

y is 0

------------

y = ++x (prefix) results in:

x is 2

y is 2

------------

In the first part of this example, you increment x alone using both prefix and
postfix increment

operators. In each, x is incremented by 1 each time. In this simple form, using
either prefix or

postfix works the same way.

In the second part of this example, you use the expression y = x++, in which the
postfix increment

operator is used. In this result, the value of x is incremented after that value
is assigned to y. Hence the

result: y is assigned the original value of x (0), and then x is incremented by
1.

In the third part, you use the prefix expression y = ++x. Here, the reverse
occurs: x is incremented

before its value is assigned to y. Because x is 1 from the previous step, its
value is incremented (to 2),

and then that value is assigned to y. Both x and y end up being 2.

Technical Note

Technically, this description is not entirely correct. In reality, Java

always completely evaluates all expressions on the right of an

expression before assigning that value to a variable, so the concept of

"assigning x to y before x is incremented" isn't precisely right.

Instead, Java takes the value of x and "remembers" it, evaluates

(increments) x, and then assigns the original value of x to y. Although

in most simple cases this distinction may not be important, for more

complex expressions with side effects, it may change the behavior of

the expression overall. See the Language Specification for many more

details about expression evaluation in Java.

Comparisons

Java has several expressions for testing equality and magnitude. All of these
expressions return a boolean

value (that is, true or false). Table 3.5 shows the comparison operators.

Table 3.5. Comparison operators.

Operator Meaning Example

== Equal x == 3

!= Not equal x != 3

< Less than x < 3

> Greater than x > 3

<= Less than or equal to x <= 3

>= Greater than or equal to x >= 3

Logical Operators

Expressions that result in boolean values (for example, the comparison
operators) can be combined by

using logical operators that represent the logical combinations AND, OR, XOR,
and logical NOT.

For AND combinations, use either the & or && operators. The entire expression
will be true only if both

expressions on either side of the operator are also true; if either expression
is false, the entire expression

is false. The difference between the two operators is in expression evaluation.
Using &, both sides of the

expression are evaluated regardless of the outcome. Using &&, if the left side
of the expression is false,

the entire expression is assumed to be false (the value of the right side
doesn't matter), so the expression

returns false, and the right side of the expression is never evaluated. (This is
often called a

"short-circuited" expression.)

For OR expressions, use either | or ||. OR expressions result in true if either
or both of the expressions

on either side is also true; if both expression operands are false, the
expression is false. As with & and

&&, the single | evaluates both sides of the expression regardless of the
outcome; and || is

short-circuited: If the left expression is true, the expression returns true and
the right side is never

evaluated.

In addition, there is the XOR operator ^, which returns true only if its
operands are different (one true

and one false, or vice versa) and false otherwise (even if both are true).

In general, only the && and || are commonly used as actual logical combinations.
&, |, and ^ are more

commonly used for bitwise logical operations.

For NOT, use the ! operator with a single expression argument. The value of the
NOT expression is the

negation of the expression; if x is true, !x is false.

Bitwise Operators

Finally, here's a short summary of the bitwise operators in Java. Most of these
expressions are inherited

from C and C++ and are used to perform operations on individual bits in
integers. This book does not go

into bitwise operations; it's an advanced topic covered better in books on C or
C++. Table 3.6

summarizes the bitwise operators.

Table 3.6. Bitwise operators.

Operator Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

<< Left shift

>> Right shift

>>> Zero fill right shift

~ Bitwise complement

<<= Left shift assignment (x = x << y)

>>= Right shift assignment (x = x >> y)

>>>= Zero fill right shift assignment (x = x

>>> y)

x&=y AND assignment (x = x & y)

x|=y OR assignment (x = x | y)

x^=y XOR assignment (x = x ^ y)

Operator Precedence

Operator precedence determines the order in which expressions are evaluated.
This, in some cases, can

determine the overall value of the expression. For example, take the following
expression:

y = 6 + 4 / 2

Depending on whether the 6 + 4 expression or the 4 / 2 expression is evaluated
first, the value of y

can end up being 5 or 8. Operator precedence determines the order in which
expressions are evaluated,

so you can predict the outcome of an expression. In general, increment and
decrement are evaluated

before arithmetic, arithmetic expressions are evaluated before comparisons, and
comparisons are

evaluated before logical expressions. Assignment expressions are evaluated last.

Table 3.7 shows the specific precedence of the various operators in Java.
Operators further up in the table

are evaluated first; operators on the same line have the same precedence and are
evaluated left to right

based on how they appear in the expression itself. For example, given that same
expression y = 6 + 4

/ 2, you now know, according to this table, that division is evaluated before
addition, so the value of y

will be 8.

Table 3.7. Operator precedence.

Operator Notes

. [] () Parentheses (()) are used to group expressions; dot

(.) is used for access to methods and variables

within objects and classes (discussed tomorrow);

square brackets ([]) are used for arrays (this is

discussed later on in the week)

++ -- ! ~

instanceof

The instanceof operator returns true or

false based on whether the object is an instance

of the named class or any of that class's subclasses

(discussed tomorrow)

new (type)expression The new operator is used for creating new instances

of classes; () in this case is for casting a value to

another type (you'll learn about both of these

tomorrow)

* / % Multiplication, division, modulus

+ - Addition, subtraction

<< >> >>> Bitwise left and right shift

< > <= >= Relational comparison tests

== != Equality

& AND

^ XOR

| OR

&& Logical AND

|| Logical OR

? : Shorthand for if...then...else (discussed on

Day 5)

= += -= *= /= %= ^= Various assignments

&= |= <<= >>= >>>= More assignments

You can always change the order in which expressions are evaluated by using
parentheses around the

expressions you want to evaluate first. You can nest parentheses to make sure
expressions evaluate in the

order you want them to (the innermost parenthetic expression is evaluated
first). The following

expression results in a value of 5, because the 6 + 4 expression is evaluated
first, and then the result of

that expression (10) is divided by 2:

y = (6 + 4) / 2

Parentheses also can be useful in cases where the precedence of an expression
isn't immediately clear-in

other words, they can make your code easier to read. Adding parentheses doesn't
hurt, so if they help you

figure out how expressions are evaluated, go ahead and use them.

String Arithmetic

One special expression in Java is the use of the addition operator (+) to create
and concatenate strings. In

most of the examples shown today and in earlier lessons, you've seen lots of
lines that looked something

like this:

System.out.println(name + " is a " + color + " beetle");

The output of that line (to the standard output) is a single string, with the
values of the variables (name

and color), inserted in the appropriate spots in the string. So what's going on
here?

The + operator, when used with strings and other objects, creates a single
string that contains the

concatenation of all its operands. If any of the operands in string
concatenation is not a string, it is

automatically converted to a string, making it easy to create these sorts of
output lines.

Technical Note

An object or type can be converted to a string if you implement the

method toString(). All objects have a default string

representation, but most classes override toString() to provide a

more meaningful printable representation.

String concatenation makes lines such as the previous one especially easy to
construct. To create a string,

just add all the parts together-the descriptions plus the variables-and print it
to the standard output, to the

screen, to an applet, or anywhere.

The += operator, which you learned about earlier, also works for strings. For
example, take the following

expression:

myName += " Jr.";

This expression is equivalent to this:

myName = myName + " Jr.";

just as it would be for numbers. In this case, it changes the value of myName,
which might be something

like John Smith to have a Jr. at the end (John Smith Jr.).

Summary

As you have learned in the last two lessons, a Java program is made up primarily
of classes and objects.

Classes and objects, in turn, are made up of methods and variables, and methods
are made up of

statements and expressions. It is those last two things that you've learned
about today; the basic building

blocks that enable you to create classes and methods and build them up to a
full-fledged Java program.

Today, you have learned about variables, how to declare them and assign values
to them; literals for

easily creating numbers, characters, and strings; and operators for arithmetic,
tests, and other simple

operations. With this basic syntax, you can move on tomorrow to learning about
working with objects

and building simple, useful Java programs.

To finish up this summary, Table 3.8 is a list of all the operators you have
learned about today so that

you can refer back to them.

Table 3.8. Operator summary.

Operator Meaning

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

== Equal

!= Not equal

&& Logical AND

|| Logical OR

! Logical NOT

& AND

| OR

^ XOR

<< Left shift

>> Right shift

>>> Zero fill right shift

~ Complement

= Assignment

++ Increment

---- Decrement

+= Add and assign

-= Subtract and assign

*= Multiply and assign

/= Divide and assign

%= Modulus and assign

&= AND and assign

|= OR and assign

<<= Left shift and assign

^= XOR and assign

>>= Right shift and assign

>>>= Zero fill right shift and assign



Q&A

Q: I didn't see any way to define constants.

A: You can't create local constants in Java; you can create only constant
instance and class

variables. You'll learn how to do this tomorrow.

Q: What happens if you assign an integer value to a variable that is too large
for that variable

to hold?

A: Logically, you would think that the variable is just converted to the next
larger type, but this isn't

what happens. What does happen is called overflow. This means that if a number
becomes too

big for its variable, that number wraps around to the smallest possible negative
number for that

type and starts counting upward toward zero again.

Because this can result in some very confusing (and wrong) results, make sure
that you declare

the right integer type for all your numbers. If there's a chance a number will
overflow its type,

use the next larger type instead.

Q: How can you find out the type of a given variable?

A: If you're using any of the primitive types (int, float, boolean), and so on,
you can't. If you

care about the type, you can convert the value to some other type by using
casting. (You'll learn

about this tomorrow.)

If you're using class types, you can use the instanceof operator, which you'll
learn more

about tomorrow.

Q: Why does Java have all these shorthand operators for arithmetic and
assignment? It's

really hard to read that way.

A: The syntax of Java is based on C++, and therefore on C. One of C's implicit
goals is the

capability of doing very powerful things with a minimum of typing. Because of
this, shorthand

operators, such as the wide array of assignments, are common.

There's no rule that says you have to use these operators in your own programs,
however. If you

find your code to be more readable using the long form, no one will come to your
house and

make you change it.

Q: You covered simple math in this section using operators. I'm assuming that
Java has ways

of doing more complex math operations?

A: You assume correctly. A special class in the java.lang package, called
java.lang.Math,

has a number of methods for exponential, trigonometric, and other basic math
operations. In fact,

because you call these methods using the Math class itself, these are prime
examples of class

methods. You'll learn more about this tomorrow.

Friday, January 4, 2008

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.