All the rar files have the same 
password : http://learning4you.blogspot.com/

Tuesday, November 25, 2008

Fashion_Model_Management_System (java major project) B.tech projects

Download Btech Projects,
Download BE projects,
Download Software Projects,
Download computer Projects,
Download Engineering Projects,
download .net projects,
download java projects,
download source code,
download php projects,
download final year projects,
download MCA projects,
Download paper presentations

DOWNLOAD PROGECTS BY CLICK ON BELOW IMAGE:

Fashion_Model_Management_System Major projects::

Credit_Card_Approval_System.zip (java major project) B.tech projects

Download Btech Projects,
Download BE projects,
Download Software Projects,
Download computer Projects,
Download Engineering Projects,
download .net projects,
download java projects,
download source code,
download php projects,
download final year projects,
download MCA projects,
Download paper presentations

DOWNLOAD PROGECT BY CLICK ON BELOW IMAGE:

Credit_Card_Approval_System Download java major projects:::::

College_Enrollment_System java major project) B.tech projects

Download Btech Projects,
Download BE projects,
Download Software Projects,
Download computer Projects,
Download Engineering Projects,
download .net projects,
download java projects,
download source code,
download php projects,
download final year projects,
download MCA projects,
Download paper presentations

DOWNLOAD PROGECTS BY CLICK ON BELOW LINK:

College_Enrollment_System.zip <-----------Download java major project

Budget_Controlling_System (java major project) B.tech projects

Download Btech Projects,
Download BE projects,
Download Software Projects,
Download computer Projects,
Download Engineering Projects,
download .net projects,
download java projects,
download source code,
download php projects,
download final year projects,
download MCA projects,
Download paper presentations

DOWNLOAD PROGECTS BY CLICK ON BELOW LINK:

Budget_Controlling_System.zip <---------- Download Java Major project

Belle_Boutique_POS_System(java major project) B.tech projects

Download Btech Projects,
Download BE projects,
Download Software Projects,
Download computer Projects,
Download Engineering Projects,
download .net projects,
download java projects,
download source code,
download php projects,
download final year projects,
download MCA projects,
Download paper presentations

DOWNLOAD PROGECTS BY CLICK ON BELOW LINK:

Belle_Boutique_POS_System.zip <--------- Download java projects

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

CollegeManagementSysyetm (java major project) B.tech projects

Download Btech Projects,
Download BE projects,
Download Software Projects,
Download computer Projects,
Download Engineering Projects,
download .net projects,
download java projects,
download source code,
download php projects,
download final year projects,
download MCA projects,
Download paper presentations

DOWNLOAD PROGECTS BY CLICK ON BELOW LINK:

CollegeManagementSysyetm java major project and some projecs:

-------------------------------------------------
click here to download
------------------------------

online_cources (java major project) B.tech projects

Download Btech Projects,
Download BE projects,
Download Software Projects,
Download computer Projects,
Download Engineering Projects,
download .net projects,
download java projects,
download source code,
download php projects,
download final year projects,
download MCA projects,
Download paper presentations

DOWNLOAD PROGECTS BY CLICK ON BELOW LINK:

online_cources java major project and some projecs:

-------------------------------------------------
click here to download
------------------------------

Simple_Library_System (java major project) B.tech projects

Download Btech Projects,
Download BE projects,
Download Software Projects,
Download computer Projects,
Download Engineering Projects,
download .net projects,
download java projects,
download source code,
download php projects,
download final year projects,
download MCA projects,
Download paper presentations

DOWNLOAD PROGECTS BY CLICK ON BELOW LINK:

Simple_Library_System java major project and some projecs:

-------------------------------------------------
click here to download
------------------------------

BugTracking_system (java major project) B.tech projects


Download Btech Projects,
Download BE projects,
Download Software Projects,
Download computer Projects,
Download Engineering Projects,
download .net projects,
download java projects,
download source code,
download php projects,
download final year projects,
download MCA projects,
Download paper presentations

DOWNLOAD PROGECTS BY CLICK ON BELOW LINK:

BugTracking_system java major project and some projecs:

-------------------------------------------------
click here to download
------------------------------

onlineshoping (java major project) B.tech projects

Download Btech Projects,
Download BE projects,
Download Software Projects,
Download computer Projects,
Download Engineering Projects,
download .net projects,
download java projects,
download source code,
download php projects,
download final year projects,
download MCA projects,
Download paper presentations

DOWNLOAD PROGECTS BY CLICK ON BELOW LINK:

onlineshoping java major project and some projecs:

-------------------------------------------------
click here to download
------------------------------

Telephone_Billing_System (java major project) B.tech project

Download Btech Projects,
Download BE projects,
Download Software Projects,
Download computer Projects,
Download Engineering Projects,
download .net projects,
download java projects,
download source code,
download php projects,
download final year projects,
download MCA projects,
Download paper presentations

DOWNLOAD PROGECTS BY CLICK ON BELOW LINK:

Telephone_Billing_System java major project and some projecs:

-----------------------------------------
click here to download
-----------------------------------------

IntranetChatting (JAVA major poject ) B.tech JAVA

Download Btech Projects,
Download BE projects,
Download Software Projects,
Download computer Projects,
Download Engineering Projects,
download .net projects,
download java projects,
download source code,
download php projects,
download final year projects,
download MCA projects,
Download paper presentations

DOWNLOAD PROGECTS BY CLICK ON BELOW LINK:

IntranetChatting java major project and some projecs:
-----------------------------------------
__________________________
click here to download
__________________________
-----------------------------------------
-----------------------------------------

Monday, November 10, 2008

Class and Object Reflection in Java

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:

  • Field, for managing and finding out information about class and instance variables
  • 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)
  • 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")
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.
  • 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.
  • java.io-Input and output classes for writing to and reading from streams (such as standard input and output) and for handling files. "Streams and I/O," describes the classes in this package.
  • 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 "Windows, Networking, and Other Tidbits," "Client/Server Networking in Java."
  • 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.
  • 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.

Comparing objects,Finding out the class of any given object

  • Comparing objects
  • Finding out the class of any given object
  • 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

Casting and Converting Objects and Primitive Types in java

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 to double
  • Casting between object types: an instance of a class to an instance of another class
  • 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.

References to objects. in java

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.

Calling Methods in java

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".
  • Line 7 calls the length() 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.
  • 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.
  • Line 13 calls the indexOf() method, which returns the position of the first instance of the given character (here, 'd').
  • 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.
  • 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);

Sunday, November 9, 2008

Accessing and Setting Class and Instance Variables

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., "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.

Creating New Objects in java

Creating New Objects

When you write a Java program, you define a set of classes. "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. , "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

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.

* Inheritance,Creating a Class Hierarchy,Single and Multiple Inheritance,Interfaces and Packages,Creating a Subclass,How Inheritance Works,




Day 2

Object-Oriented Programming and Java

by Laura Lemay

CONTENTS


Object-oriented programming (OOP) is one of the biggest programming ideas of recent years, and you might worry that you must spend years 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 made up of many kinds of smaller objects. This capability of combining objects, however, is only one very general aspect of object-oriented programming. Object-oriented programming 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:
  • Color: red, green, silver, brown
  • Style: cruiser, sport bike, standard
  • 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:
  • Start the engine
  • Stop the engine
  • Speed up
  • Change gear
  • 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 class definition easier for you and other people to read. The indentation used here, with instance variables and methods indented from the class definition, is the style used throughout this book. The Java class libraries use a similar indentation. You can choose any indentation style that 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.
  • 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.
For example, let's go back to that Motorcycle class and pretend 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:

  • 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.
  • 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.

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.
  • 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.
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 tag as you did yesterday. Here's an HTML file to use:


Another Applet


My second Java applet says:




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.








Related Posts with Thumbnails