- •CONTENTS
- •1.1 Introduction
- •1.2 What Is a Computer?
- •1.3 Programs
- •1.4 Operating Systems
- •1.5 Java, World Wide Web, and Beyond
- •1.6 The Java Language Specification, API, JDK, and IDE
- •1.7 A Simple Java Program
- •1.8 Creating, Compiling, and Executing a Java Program
- •1.9 (GUI) Displaying Text in a Message Dialog Box
- •2.1 Introduction
- •2.2 Writing Simple Programs
- •2.3 Reading Input from the Console
- •2.4 Identifiers
- •2.5 Variables
- •2.7 Named Constants
- •2.8 Numeric Data Types and Operations
- •2.9 Problem: Displaying the Current Time
- •2.10 Shorthand Operators
- •2.11 Numeric Type Conversions
- •2.12 Problem: Computing Loan Payments
- •2.13 Character Data Type and Operations
- •2.14 Problem: Counting Monetary Units
- •2.15 The String Type
- •2.16 Programming Style and Documentation
- •2.17 Programming Errors
- •2.18 (GUI) Getting Input from Input Dialogs
- •3.1 Introduction
- •3.2 boolean Data Type
- •3.3 Problem: A Simple Math Learning Tool
- •3.4 if Statements
- •3.5 Problem: Guessing Birthdays
- •3.6 Two-Way if Statements
- •3.7 Nested if Statements
- •3.8 Common Errors in Selection Statements
- •3.9 Problem: An Improved Math Learning Tool
- •3.10 Problem: Computing Body Mass Index
- •3.11 Problem: Computing Taxes
- •3.12 Logical Operators
- •3.13 Problem: Determining Leap Year
- •3.14 Problem: Lottery
- •3.15 switch Statements
- •3.16 Conditional Expressions
- •3.17 Formatting Console Output
- •3.18 Operator Precedence and Associativity
- •3.19 (GUI) Confirmation Dialogs
- •4.1 Introduction
- •4.2 The while Loop
- •4.3 The do-while Loop
- •4.4 The for Loop
- •4.5 Which Loop to Use?
- •4.6 Nested Loops
- •4.7 Minimizing Numeric Errors
- •4.8 Case Studies
- •4.9 Keywords break and continue
- •4.10 (GUI) Controlling a Loop with a Confirmation Dialog
- •5.1 Introduction
- •5.2 Defining a Method
- •5.3 Calling a Method
- •5.4 void Method Example
- •5.5 Passing Parameters by Values
- •5.6 Modularizing Code
- •5.7 Problem: Converting Decimals to Hexadecimals
- •5.8 Overloading Methods
- •5.9 The Scope of Variables
- •5.10 The Math Class
- •5.11 Case Study: Generating Random Characters
- •5.12 Method Abstraction and Stepwise Refinement
- •6.1 Introduction
- •6.2 Array Basics
- •6.3 Problem: Lotto Numbers
- •6.4 Problem: Deck of Cards
- •6.5 Copying Arrays
- •6.6 Passing Arrays to Methods
- •6.7 Returning an Array from a Method
- •6.8 Variable-Length Argument Lists
- •6.9 Searching Arrays
- •6.10 Sorting Arrays
- •6.11 The Arrays Class
- •7.1 Introduction
- •7.2 Two-Dimensional Array Basics
- •7.3 Processing Two-Dimensional Arrays
- •7.4 Passing Two-Dimensional Arrays to Methods
- •7.5 Problem: Grading a Multiple-Choice Test
- •7.6 Problem: Finding a Closest Pair
- •7.7 Problem: Sudoku
- •7.8 Multidimensional Arrays
- •8.1 Introduction
- •8.2 Defining Classes for Objects
- •8.3 Example: Defining Classes and Creating Objects
- •8.4 Constructing Objects Using Constructors
- •8.5 Accessing Objects via Reference Variables
- •8.6 Using Classes from the Java Library
- •8.7 Static Variables, Constants, and Methods
- •8.8 Visibility Modifiers
- •8.9 Data Field Encapsulation
- •8.10 Passing Objects to Methods
- •8.11 Array of Objects
- •9.1 Introduction
- •9.2 The String Class
- •9.3 The Character Class
- •9.4 The StringBuilder/StringBuffer Class
- •9.5 Command-Line Arguments
- •9.6 The File Class
- •9.7 File Input and Output
- •9.8 (GUI) File Dialogs
- •10.1 Introduction
- •10.2 Immutable Objects and Classes
- •10.3 The Scope of Variables
- •10.4 The this Reference
- •10.5 Class Abstraction and Encapsulation
- •10.6 Object-Oriented Thinking
- •10.7 Object Composition
- •10.8 Designing the Course Class
- •10.9 Designing a Class for Stacks
- •10.10 Designing the GuessDate Class
- •10.11 Class Design Guidelines
- •11.1 Introduction
- •11.2 Superclasses and Subclasses
- •11.3 Using the super Keyword
- •11.4 Overriding Methods
- •11.5 Overriding vs. Overloading
- •11.6 The Object Class and Its toString() Method
- •11.7 Polymorphism
- •11.8 Dynamic Binding
- •11.9 Casting Objects and the instanceof Operator
- •11.11 The ArrayList Class
- •11.12 A Custom Stack Class
- •11.13 The protected Data and Methods
- •11.14 Preventing Extending and Overriding
- •12.1 Introduction
- •12.2 Swing vs. AWT
- •12.3 The Java GUI API
- •12.4 Frames
- •12.5 Layout Managers
- •12.6 Using Panels as Subcontainers
- •12.7 The Color Class
- •12.8 The Font Class
- •12.9 Common Features of Swing GUI Components
- •12.10 Image Icons
- •13.1 Introduction
- •13.2 Exception-Handling Overview
- •13.3 Exception-Handling Advantages
- •13.4 Exception Types
- •13.5 More on Exception Handling
- •13.6 The finally Clause
- •13.7 When to Use Exceptions
- •13.8 Rethrowing Exceptions
- •13.9 Chained Exceptions
- •13.10 Creating Custom Exception Classes
- •14.1 Introduction
- •14.2 Abstract Classes
- •14.3 Example: Calendar and GregorianCalendar
- •14.4 Interfaces
- •14.5 Example: The Comparable Interface
- •14.6 Example: The ActionListener Interface
- •14.7 Example: The Cloneable Interface
- •14.8 Interfaces vs. Abstract Classes
- •14.9 Processing Primitive Data Type Values as Objects
- •14.10 Sorting an Array of Objects
- •14.11 Automatic Conversion between Primitive Types and Wrapper Class Types
- •14.12 The BigInteger and BigDecimal Classes
- •14.13 Case Study: The Rational Class
- •15.1 Introduction
- •15.2 Graphical Coordinate Systems
- •15.3 The Graphics Class
- •15.4 Drawing Strings, Lines, Rectangles, and Ovals
- •15.5 Case Study: The FigurePanel Class
- •15.6 Drawing Arcs
- •15.7 Drawing Polygons and Polylines
- •15.8 Centering a String Using the FontMetrics Class
- •15.9 Case Study: The MessagePanel Class
- •15.10 Case Study: The StillClock Class
- •15.11 Displaying Images
- •15.12 Case Study: The ImageViewer Class
- •16.1 Introduction
- •16.2 Event and Event Source
- •16.3 Listeners, Registrations, and Handling Events
- •16.4 Inner Classes
- •16.5 Anonymous Class Listeners
- •16.6 Alternative Ways of Defining Listener Classes
- •16.7 Problem: Loan Calculator
- •16.8 Window Events
- •16.9 Listener Interface Adapters
- •16.10 Mouse Events
- •16.11 Key Events
- •16.12 Animation Using the Timer Class
- •17.1 Introduction
- •17.2 Buttons
- •17.3 Check Boxes
- •17.4 Radio Buttons
- •17.5 Labels
- •17.6 Text Fields
- •17.7 Text Areas
- •17.8 Combo Boxes
- •17.9 Lists
- •17.10 Scroll Bars
- •17.11 Sliders
- •17.12 Creating Multiple Windows
- •18.1 Introduction
- •18.2 Developing Applets
- •18.3 The HTML File and the <applet> Tag
- •18.4 Applet Security Restrictions
- •18.5 Enabling Applets to Run as Applications
- •18.6 Applet Life-Cycle Methods
- •18.7 Passing Strings to Applets
- •18.8 Case Study: Bouncing Ball
- •18.9 Case Study: TicTacToe
- •18.10 Locating Resources Using the URL Class
- •18.11 Playing Audio in Any Java Program
- •18.12 Case Study: Multimedia Animations
- •19.1 Introduction
- •19.2 How is I/O Handled in Java?
- •19.3 Text I/O vs. Binary I/O
- •19.4 Binary I/O Classes
- •19.5 Problem: Copying Files
- •19.6 Object I/O
- •19.7 Random-Access Files
- •20.1 Introduction
- •20.2 Problem: Computing Factorials
- •20.3 Problem: Computing Fibonacci Numbers
- •20.4 Problem Solving Using Recursion
- •20.5 Recursive Helper Methods
- •20.6 Problem: Finding the Directory Size
- •20.7 Problem: Towers of Hanoi
- •20.8 Problem: Fractals
- •20.9 Problem: Eight Queens
- •20.10 Recursion vs. Iteration
- •20.11 Tail Recursion
- •APPENDIXES
- •INDEX
462 Chapter 14 Abstract Classes and Interfaces
Note that you could not define the equalArea method for comparing whether two geometric objects have the same area if the getArea method were not defined in GeometricObject.
why abstract methods? So, you see the benefits of defining the abstract methods in GeometricObject.
abstract method in abstract class
object cannot be created from abstract class
abstract class without abstract method
superclass of abstract class may be concrete
concrete method overridden to be abstract
abstract class as type
14.2.2Interesting Points on Abstract Classes
The following points on abstract classes are worth noting:
■An abstract method cannot be contained in a nonabstract class. If a subclass of an abstract superclass does not implement all the abstract methods, the subclass must be defined abstract. In other words, in a nonabstract subclass extended from an abstract class, all the abstract methods must be implemented. Also note that abstract methods are nonstatic.
■An abstract class cannot be instantiated using the new operator, but you can still define its constructors, which are invoked in the constructors of its subclasses. For instance, the constructors of GeometricObject are invoked in the Circle class and the Rectangle class.
■A class that contains abstract methods must be abstract. However, it is possible to define an abstract class that contains no abstract methods. In this case, you cannot create instances of the class using the new operator. This class is used as a base class for defining a new subclass.
■A subclass can be abstract even if its superclass is concrete. For example, the Object class is concrete, but its subclasses, such as GeometricObject, may be abstract.
■A subclass can override a method from its superclass to define it abstract. This is very unusual but is useful when the implementation of the method in the superclass becomes invalid in the subclass. In this case, the subclass must be defined abstract.
■You cannot create an instance from an abstract class using the new operator, but an abstract class can be used as a data type. Therefore, the following statement, which creates an array whose elements are of the GeometricObject type, is correct.
GeometricObject[] objects = new GeometricObject[10];
You can then create an instance of GeometricObject and assign its reference to the array like this:
objects[0] = new Circle();
Video Note
Calendar and Gregorian-
Calendar Classes
abstract add method
constructing calendar
get(field)
14.3 Example: Calendar and GregorianCalendar
An instance of java.util.Date represents a specific instant in time with millisecond precision. java.util.Calendar is an abstract base class for extracting detailed calendar information, such as year, month, date, hour, minute, and second. Subclasses of Calendar can implement specific calendar systems, such as the Gregorian calendar, the lunar calendar, and the Jewish calendar. Currently, java.util.GregorianCalendar for the Gregorian calendar is supported in Java, as shown in Figure 14.3. The add method is abstract in the Calendar class, because its implementation is dependent on a concrete calendar system.
You can use new GregorianCalendar() to construct a default GregorianCalendar with the current time and new GregorianCalendar(year, month, date) to construct a GregorianCalendar with the specified year, month, and date. The month parameter is 0 based—that is, 0 is for January.
The get(int field) method defined in the Calendar class is useful for extracting the date and time information from a Calendar object. The fields are defined as constants, as shown in Table 14.1.
14.3 Example: Calendar and GregorianCalendar 463 |
|||
java.util.Calendar |
|
|
|
|
|
|
|
#Calendar() |
|
Constructs a default calendar. |
|
+get(field: int): int |
|
Returns the value of the given calendar field. |
|
+set(field: int, value: int): void |
|
Sets the given calendar to the specified value. |
|
+set(year: int, month: int, |
|
Sets the calendar with the specified year, month, and date. The month |
|
dayOfMonth: int): void |
|
parameter is 0 based; that is, 0 is for January. |
|
+getActualMaximum(field: int): int |
|
Returns the maximum value that the specified calendar field could have. |
|
+add(field: int, amount: int): void |
|
Adds or subtracts the specified amount of time to the given calendar field. |
|
+getTime(): java.util.Date |
|
Returns a Date object representing this calendar’s time value (million |
|
|
|
second offset from the Unix epoch). |
|
+setTime(date: java.util.Date): void |
|
Sets this calendar’s time with the given Date object. |
|
java.util.GregorianCalendar |
|
|
|
|
|
|
|
|
|
|
|
+GregorianCalendar() |
|
Constructs a GregorianCalendar for the current time. |
|
+GregorianCalendar(year: int, |
|
Constructs a GregorianCalendar for the specified year, month, and |
|
month: int, dayOfMonth: int) |
|
day of month. |
|
+GregorianCalendar(year: int, |
|
Constructs a GregorianCalendar for the specified year, month, day of |
|
month: int, dayOfMonth: int, |
|
month, hour, minute, and second. The month parameter is 0 based; that |
|
hour:int, minute: int, second: int) |
|
is, 0 is for January. |
|
|
|
|
|
FIGURE 14.3 The abstract Calendar class defines common features of various calendars.
TABLE 14.1 Field constants in the Calendar class
Constant |
Description |
|
|
YEAR |
The year of the calendar. |
MONTH |
The month of the calendar with 0 for January. |
DATE |
The day of the calendar. |
HOUR |
The hour of the calendar (12-hour notation). |
HOUR_OF_DAY |
The hour of the calendar (24-hour notation). |
MINUTE |
The minute of the calendar. |
SECOND |
The second of the calendar. |
DAY_OF_WEEK |
The day number within the week with 1 for Sunday. |
DAY_OF_MONTH |
Same as DATE. |
DAY_OF_YEAR |
The day number in the year with 1 for the first day of the year. |
WEEK_OF_MONTH |
The week number within the month with 1 for the first week. |
WEEK_OF_YEAR |
The week number within the year with 1 for the first week. |
AM_PM |
Indicator for AM or PM (0 for AM and 1 for PM). |
Listing 14.5 gives an example that displays the date and time information for the current time.
LISTING 14.5 TestCalendar.java
1 import java.util.*;
2
3 public class TestCalendar {
4 public static void main(String[] args) {
464 Chapter 14 |
Abstract Classes and Interfaces |
||
|
5 |
// Construct a Gregorian calendar for the current date and time |
|
calendar for current time |
6 |
Calendar calendar = new GregorianCalendar(); |
|
|
7 |
System.out.println("Current time is " + new Date()); |
|
extract fields in calendar |
8 |
System.out.println("YEAR:\t" + calendar.get(Calendar.YEAR)); |
|
|
9 |
System.out.println("MONTH:\t" + calendar.get(Calendar.MONTH)); |
10System.out.println("DATE:\t" + calendar.get(Calendar.DATE));
11System.out.println("HOUR:\t" + calendar.get(Calendar.HOUR));
12System.out.println("HOUR_OF_DAY:\t" +
13calendar.get(Calendar.HOUR_OF_DAY));
14System.out.println("MINUTE:\t" + calendar.get(Calendar.MINUTE));
15System.out.println("SECOND:\t" + calendar.get(Calendar.SECOND));
16System.out.println("DAY_OF_WEEK:\t" +
17calendar.get(Calendar.DAY_OF_WEEK));
18System.out.println("DAY_OF_MONTH:\t" +
19calendar.get(Calendar.DAY_OF_MONTH));
20System.out.println("DAY_OF_YEAR: " +
21calendar.get(Calendar.DAY_OF_YEAR));
22System.out.println("WEEK_OF_MONTH: " +
23calendar.get(Calendar.WEEK_OF_MONTH));
24System.out.println("WEEK_OF_YEAR: " +
25calendar.get(Calendar.WEEK_OF_YEAR));
26System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
|
27 |
|
|
|
|
28 |
// Construct a calendar for September 11, 2001 |
||
create a calendar |
29 |
|
Calendar calendar1 = new GregorianCalendar(2001, 8, 11); |
|
|
30 |
System.out.println("September 11, 2001 is a " + |
||
|
31 |
|
dayNameOfWeek(calendar1.get(Calendar.DAY_OF_WEEK))); |
|
|
32 |
} |
|
|
|
33 |
|
|
|
|
34 |
public static String dayNameOfWeek(int dayOfWeek) { |
||
|
35 |
|
switch |
(dayOfWeek) { |
|
36 |
|
case |
1: return "Sunday"; |
|
37 |
|
case |
2: return "Monday"; |
|
38 |
|
case |
3: return "Tuesday"; |
|
39 |
|
case |
4: return "Wednesday"; |
|
40 |
|
case |
5: return "Thursday"; |
|
41 |
|
case |
6: return "Friday"; |
|
42 |
|
case |
7: return "Saturday"; |
|
43 |
|
default: return null; |
|
|
44 |
} |
|
|
|
45 |
} |
|
|
|
46 |
} |
|
|
Current time is Sun Sep 09 21:23:59 EDT 2007
YEAR: |
2007 |
MONTH: |
8 |
DATE: |
9 |
HOUR: |
9 |
HOUR_OF_DAY: |
21 |
MINUTE: |
23 |
SECOND: |
59 |
DAY_OF_WEEK: |
1 |
DAY_OF_MONTH: |
9 |
DAY_OF_YEAR: |
252 |
WEEK_OF_MONTH: |
3 |
WEEK_OF_YEAR: |
37 |
AM_PM: |
1 |
September 11, 2001 is a Tuesday
|
14.4 Interfaces 465 |
The set(int field, value) method defined in the Calendar class can be used to set a |
set(field, value) |
field. For example, you can use calendar.set(Calendar.DAY_OF_MONTH, 1) to set the |
|
calendar to the first day of the month. |
|
The add(field, value) method adds the specified amount to a given field. For example, |
add(field, amount) |
add(Calendar.DAY_OF_MONTH, 5) adds five days to the current time of the calendar. |
|
add(Calendar.DAY_OF_MONTH, -5) subtracts five days from the current time of the calendar. |
|
To obtain the number of days in a month, use calendar.getActualMaximum(Cal- |
getActualMaximum(field) |
endar.DAY_OF_MONTH). For example, if the calendar were for March, this method would |
|
return 31. |
|
You can set a time represented in a Date object for the calendar by invoking |
setTime(Date) |
calendar. setTime(date) and retrieve the time by invoking calendar. getTime(). |
getTime() |
14.4 Interfaces
An interface is a classlike construct that contains only constants and abstract methods. In many ways an interface is similar to an abstract class, but its intent is to specify common behavior for objects. For example, using appropriate interfaces, you can specify that the objects are comparable, edible, and/or cloneable.
To distinguish an interface from a class, Java uses the following syntax to define an interface:
modifier interface InterfaceName { /** Constant declarations */
/** Method signatures */
}
Here is an example of an interface:
public interface Edible { /** Describe how to eat */
public abstract String howToEat();
}
Video Note
The concept of interface
An interface is treated like a special class in Java. Each interface is compiled into a separate bytecode file, just like a regular class. As with an abstract class, you cannot create an instance from an interface using the new operator, but in most cases you can use an interface more or less the same way you use an abstract class. For example, you can use an interface as a data type for a reference variable, as the result of casting, and so on.
You can now use the Edible interface to specify whether an object is edible. This is accomplished by letting the class for the object implement this interface using the implements keyword. For example, the classes Chicken and Fruit in Listing 14.6 (lines 14, 23) implement the Edible interface. The relationship between the class and the interface
is known as interface inheritance. Since interface inheritance and class inheritance are essen- interface inheritance tially the same, we will simply refer to both as inheritance.
LISTING 14.6 TestEdible.java
1 public class TestEdible {
2public static void main(String[] args) {
3 Object[] objects = {new Tiger(), new Chicken(), new Apple()}; 4 for (int i = 0; i < objects.length; i++)
5if (objects[i] instanceof Edible)
6System.out.println(((Edible)objects[i]).howToEat());
7 |
} |
|
8 |
} |
|
9 |
|
|
10 |
class Animal { |
Animal class |
466 Chapter 14 |
Abstract Classes and Interfaces |
|||||||
|
11 |
|
|
// Data fields, constructors, and methods omitted here |
||||
|
12 |
} |
|
|
|
|
|
|
|
13 |
|
|
|
|
|
|
|
implements Edible |
14 |
class Chicken extends Animal implements Edible { |
|
|||||
howToEat() |
15 |
|
|
public String howToEat() { |
|
|
||
|
16 |
|
|
return "Chicken: Fry it"; |
||||
|
17 |
} |
|
|
|
|
||
|
18 |
} |
|
|
|
|
|
|
|
19 |
|
|
|
|
|
|
|
Tiger class |
20 class Tiger extends Animal { |
|||||||
|
21 |
} |
|
|
|
|
|
|
|
22 |
|
|
|
|
|
|
|
implements Edible |
23 |
abstract class Fruit implements Edible { |
|
|
||||
|
24 |
|
// Data fields, constructors, and methods omitted here |
|||||
|
25 |
} |
|
|
|
|
|
|
|
26 |
|
|
|
|
|
|
|
Apple class |
27 class Apple extends Fruit { |
|||||||
|
28 |
|
|
public String howToEat() { |
|
|
|
|
|
29 |
|
|
return "Apple: Make apple cider"; |
||||
|
30 |
} |
|
|
|
|
||
|
31 |
} |
|
|
|
|
|
|
|
32 |
|
|
|
|
|
|
|
Orange class |
33 class Orange extends Fruit { |
|||||||
|
34 |
|
|
public String howToEat() { |
|
|
|
|
|
35 |
|
|
return "Orange: Make orange juice"; |
||||
|
36 |
} |
|
|
|
|
||
|
37 |
} |
|
|
|
|
|
Chicken: Fry it
Apple: Make apple cider
The Chicken class extends Animal and implements Edible to specify that chickens are edible. When a class implements an interface, it implements all the methods defined in the interface with the exact signature and return type. The Chicken class implements the howToEat method (lines 15–17).
The Fruit class implements Edible. Since it does not implement the howToEat method, Fruit must be denoted abstract (line 23). The concrete subclasses of Fruit must implement the howToEat method. The Apple and Orange classes implements the howToEat method (lines 28, 34).
The main method creates an array with three objects for Tiger, Chicken, and Apple (line 3) and invokes the howToEat method if the element is edible (line 6).
Note
Since all data fields are public final static and all methods are public abstract in an omitting modifiers interface, Java allows these modifiers to be omitted. Therefore the following interface definitions
are equivalent:
public interface T { |
|
|
|
public interface T { |
|||
|
public static |
final int K = 1; |
|
Equivalent |
int K = 1; |
||
|
|
|
|
|
void p(); |
||
|
public abstract |
void p(); |
|
|
|
||
|
|
|
|
||||
} |
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
|