Sie sind auf Seite 1von 8

Content Introduction to JAVA Features Data Types Classes, Objects and methods Inheritance GUI Components Swing Components

Adapter Handling Event Handling Layout Managers Graphics and Java2D Packages Files and Streams Exception Handling 9

UNIT III How to program

The Complete Reference, Fifth Edition

41 82 189 510

653 595 223 672 638 UNIT IV 273 249

Multithreading Applets JDBC database programming Introduction to Servlets Network Programming RMI

1052 958 1189 1236 1106

627

587

UNIT V Byte code Interpretation Customizing application Data Structures Collection classes Activation Object serialization Distributed garbage collection JINI overview

817

History of Java The microprocessor revolution's most important contribution to date is that it made possible the development of personal computers, which now number in the hundreds of millions worldwide. Personal computers have profoundly affected people's lives and the ways organizations conduct and manage their business. Microprocessors are having a profound impact in intelligent consumer-electronic devices. Recognizing this, Sun Microsystems in 1991 funded an internal corporate research project codenamed Green, which resulted in the development of a C++-based language that its creator, James Gosling, called Oak after an oak tree outside his window at Sun. It was later discovered that there already was a computer language called Oak. When a group of Sun people visited a local coffee shop, the name Java was suggested, and it stuck. The Green project ran into some difficulties. The marketplace for intelligent consumer-electronic devices was not developing in the early 1990s as quickly as Sun had anticipated. The project was in danger of being canceled. By sheer good fortune, the World Wide Web exploded in popularity in 1993, and Sun people saw the immediate potential of using Java to add dynamic content, such as interactivity and animations, to Web pages. This breathed new life into the project. Sun formally announced Java at a major conference in May 1995. Java garnered the attention of the business community because of the phenomenal interest in the World Wide Web. Java is now used to develop large-scale enterprise applications, to enhance the functionality of Web servers (the computers that provide the content we see in our Web browsers), to provide applications for consumer devices (e.g., cell phones, pagers and personal digital assistants) and for many other purposes.

Introduction to Classes and Objects: We introduced the basic terminology and concepts of object-oriented programming in Section 1.16. In Chapter 2, you began to use those concepts to create simple applications that displayed messages to the user, obtained information from the user, performed calculations and made decisions. One common feature of every application in Chapter 2 was that all the statements that performed tasks were located in method main. Typically, the applications you develop in this book will consist of two or more classes, each containing one or more methods. If you become part of a development team in industry, you might work on applications that contain hundreds, or even thousands, of classes. In this chapter, we present a simple framework for organizing objectoriented applications in Java. First, we motivate the notion of classes with a real-world example. Then we present five complete working applications to demonstrate creating and using your own classes. The first four of these examples begin our case study on developing a grade-book class that instructors can use to maintain student test scores. This case study is enhanced over the next several chapters, culminating with the version presented in Chapter 7, Arrays. The last example in the chapter introduces floating-point numbersthat is, numbers containing decimal points, such as 0.0345, 7.23 and 100.7in the context of a bank account class that maintains a customer's balance.

Classes, Objects, Methods and Instance Variables Let's begin with a simple analogy to help you understand classes and their contents. Suppose you want to drive a car and make it go faster by pressing down on its accelerator pedal. What must happen before you can do this? Well, before you can drive a car, someone has to design the car. A car typically begins as engineering drawings, similar to the blueprints used to design a house. These engineering drawings include the design for an accelerator pedal to make the car go faster. The pedal "hides" the complex mechanisms that actually make the car go faster, just as the brake pedal "hides" the mechanisms that slow the car and the steering wheel "hides" the mechanisms that turn the car. This enables people with little or no knowledge of how engines work to drive a car easily.

Unfortunately, you cannot drive the engineering drawings of a car. Before you can drive a car, the car must be built from the engineering drawings that describe it. A completed car will have an actual accelerator pedal to make the car go faster, but even that's not enoughthe car will not accelerate on its own, so the driver must press the accelerator pedal. Now let's use our car example to introduce the key programming concepts of this section. Performing a task in a program requires a method. The method describes the mechanisms that actually perform its tasks. The method hides from its user the complex tasks that it performs, just as the accelerator pedal of a car hides from the driver the complex mechanisms of making the car go faster. In Java, we begin by creating a program unit called a class to house a method, just as a car's engineering drawings house the design of an accelerator pedal. In a class, you provide one or more methods that are designed to perform the class's tasks. For example, a class that represents a bank account might contain one method to deposit money to an account, another to withdraw money from an account and a third to inquire what the current balance is. Just as you cannot drive an engineering drawing of a car, you cannot "drive" a class. Just as someone has to build a car from its engineering drawings before you can actually drive a car, you must build an object of a class before you can get a program to perform the tasks the class describes how to do. That is one reason Java is known as an object-oriented programming language. When you drive a car, pressing its gas pedal sends a message to the car to perform a taskthat is, make the car go faster. Similarly, you send messages to an objecteach message is known as a method call and tells a method of the object to perform its task. Thus far, we have used the car analogy to introduce classes, objects and methods. In addition to the capabilities a car provides, it also has many attributes, such as its color, the number of doors, the amount of gas in its tank, its current speed and its total miles driven (i.e., its odometer reading). Like the car's capabilities, these attributes are represented as part of a car's design in its engineering diagrams. As you drive a car, these attributes are always associated with the car. Every car maintains its own attributes. For example, each car knows how much gas is in its own gas tank, but not how much is in the tanks of other cars. Similarly, an object has attributes that are carried with the object as it is used in a program. These attributes are specified as part of the object's class. For example, a bank account object has a balance attribute that represents the amount of money in the account. Each bank account object knows the balance in the account it represents, but not the balances of the other accounts in the bank. Attributes are specified by the class's instance variables.

The remainder of this chapter presents examples that demonstrate the concepts we introduced in the context of the car analogy. The first four examples, summarized below, incrementally build a GradeBook class to demonstrate these concepts: 1. The first example presents a GradeBook class with one method that simply displays a welcome message when it is called. We then show how to create an object of that class and call the method so that it displays the welcome message. 2. The second example modifies the first by allowing the method to receive a course name as an argument and by displaying the name as part of the welcome message. 3. The third example shows how to store the course name in a GradeBook object. For this version of the class, we also show how to use methods to set the course name and obtain the course name. 4. The fourth example demonstrates how the data in a GradeBook object can be initialized when the object is createdthe initialization is performed by the class's constructor. The last example in the chapter presents an Account class that reinforces the concepts presented in the first four examples and introduces floating-point numbersnumbers containing decimal points, such as 0.0345, 7.23 and 100.7. For this purpose, we present an Account class that represents a bank account and maintains its balance as a floating-point number. The class contains two methodsone that credits a deposit to the account, thus increasing the balance, and another that retrieves the balance. The class's constructor allows the balance of each Account object to be initialized as the object is created. We create two Account objects and make deposits into each to show that each object maintains its own balance. The example also demonstrates how to input and display floating-point numbers. Declaring a Class with a Method and Instantiating an Object of a Class We begin with an example that consists of classes GradeBook (Fig. 3.1) and GradeBookTest (Fig. 3.2). Class GradeBook (declared in file GradeBook.java) will be used to display a message on the screen (Fig. 3.2) welcoming the instructor to the grade-book application. Class GradeBookTest (declared in file GradeBookTest.java) is an application class in which the main method will use class GradeBook. Each class declaration that begins with keyword public must be stored in a file that has the same name as the class and ends with the .java file-name extension. Thus, classes GradeBook and GradeBookTest must be declared in separate files, because each class is declared public.

Figure 3.1. Class declaration with one method.

1 // Fig. 3.1: GradeBook.java 2 // Class declaration with one method. 3 4 public class GradeBook 5 { 6 // display a welcome message to the GradeBook user 7 public void displayMessage() 8 { 9 System.out.println( "Welcome to the Grade Book!" ); 10 } // end method displayMessage 11 12 } // end class GradeBook

Figure 3.2. Creating an object of class GradeBook and calling its displayMessage method. 1 // Fig. 3.2: GradeBookTest.java 2 // Create a GradeBook object and call its displayMessage method. 3 4 public class GradeBookTest 5 { 6 // main method begins program execution 7 public static void main( String args[] ) 8 { 9 // create a GradeBook object and assign it to myGradeBook 10 GradeBook myGradeBook = new GradeBook(); 11 12 // call myGradeBook's displayMessage method 13 myGradeBook.displayMessage(); 14 } // end main 15 16 } // end class GradeBookTest

Welcome to the Grade Book!

Welcome to the Grade Book! Common Programming Error 3.1 Declaring more than one public class in the same file is a compilation error. Class GradeBook The GradeBook class declaration (Fig. 3.1) contains a displayMessage method (lines 710) that displays a message on the screen. Line 9 of the class performs the work of displaying the message.

Recall that a class is like a blueprintwe'll need to make an object of this class and call its method to get line 9 to execute and display its message. The class declaration begins at line 4. The keyword public is an access modifier. For now, we will simply declare every class public. Every class declaration contains keyword class followed immediately by the class's name. Every class's body is enclosed in a pair of left and right braces ({ and }), as in lines 5 and 12 of class GradeBook. In Chapter 2, each class we declared had one method named main. Class GradeBook also has one methoddisplayMessage (lines 710). Recall that main is a special method that is always called automatically by the Java Virtual Machine (JVM) when you execute an application. Most methods do not get called automatically. As you will soon see, you must call method displayMessage to tell it to perform its task. The method declaration begins with keyword public to indicate that the method is "available to the public"that is, it can be called from outside the class declaration's body by methods of other classes. Keyword void indicates that this method will perform a task but will not return (i.e., give back) any information to its calling method when it completes its task. You have already used methods that return informationfor example, in Chapter 2 you used Scanner method nextInt to input an integer typed by the user at the keyboard. When nextInt inputs a value, it returns that value for use in the program. The name of the method, displayMessage, follows the return type. By convention, method names begin with a lowercase first letter and all subsequent words in the name begin with a capital letter. The parentheses after the method name indicate that this is a method. An empty set of parentheses, as shown in line 7, indicates that this method does not require additional information to perform its task. Line 7 is commonly referred to as the method header. Every method's body is delimited by left and right braces ({ and }), as in lines 8 and 10. The body of a method contains statement(s) that perform the method's task. In this case, the method contains one statement (line 9) that displays the message "Welcome to the Grade Book!" followed by a newline in the command window. After this statement executes, the method has completed its task. Next, we'd like to use class GradeBook in an application. As you learned in Chapter 2, method main begins the execution of every application. A class that contains method main is a Java application. Such a class is special because the JVM can use main to begin execution. Class GradeBook is not an application because it does not contain main. Therefore, if you try to execute GradeBook by typing java GradeBook in the command window, you will get the error message: Exception in thread "main" java.lang.NoSuchMethodError: main This was not a problem in Chapter 2, because every class you declared had a main method. To fix this problem for the GradeBook, we must either declare a separate class that contains a main method or place a main method in class GradeBook. To help you prepare for the larger programs you will encounter later in this book and in industry, we use a separate class (GradeBookTest in this example) containing method main to test each new class we create in this chapter.

Class GradeBookTest The GradeBookTest class declaration (Fig. 3.2) contains the main method that will control our application's execution. Any class that contains main declared as shown on line 7 can be used to execute an application. This class declaration begins at line 4 and ends at line 16. The class contains only a main method, which is typical of many classes that begin an application's execution.

Das könnte Ihnen auch gefallen