Lập trình Java - Phần 2
Chia sẻ bởi Nguyễn Bùi Minh Tâm |
Ngày 19/03/2024 |
13
Chia sẻ tài liệu: Lập trình Java - Phần 2 thuộc Công nghệ thông tin
Nội dung tài liệu:
11/20/2009
Võ Phương Bình - ITFAC - DLU
1
Part II: Object-Oriented Programming
Chapter 6: Object-Oriented Programming
Chapter 7: Strings
11/20/2009
Võ Phương Bình - ITFAC - DLU
2
Chapter 6: Object-Oriented Programming
Introduction
Superclasses and Subclasses
protected Members
Relationship between Superclass Objects and Subclass Objects
Implicit Subclass-Object-to-Superclass-Object Conversion
Composition vs. Inheritance
Introduction to Polymorphism
11/20/2009
Võ Phương Bình - ITFAC - DLU
3
Chapter 6: Object-Oriented Programming
Dynamic Method Binding
final Methods and Classes
Abstract Superclasses and Concrete Classes
Polymorphism Example
New Classes and Dynamic Binding
Inheriting Interface and Implementation
Creating and Using Interfaces
Inner Class Definitions
Notes on Inner Class Definitions
11/20/2009
Võ Phương Bình - ITFAC - DLU
4
Introduction
Object-Oriented Programming (OOP)
Inheritance - form of software reusability
New classes created from existing ones
Absorb attributes and behaviors, and add in their own
Override methods - redefine inherited methods
Subclass inherits from superclass
Direct superclass - subclass explicitly inherits
Indirect superclass - subclass inherits from two or more levels up the class hierarchy
Polymorphism
Write programs in a general fashion to handle a wide variety of classes
Abstraction - seeing the big picture
11/20/2009
Võ Phương Bình - ITFAC - DLU
5
Introduction, cont
Object-Oriented Programming
Introduce protected member access
Relationships
"is a" - inheritance
Object of subclass "is a" object of the superclass
"has a" - composition
Object "has a" object of another class as a member
Class libraries
New classes can inherit from them
Someday software may be constructed from standardized, reusable components (like hardware)
Create more powerful software
11/20/2009
Võ Phương Bình - ITFAC - DLU
6
Superclasses and Subclasses
Inheritance example
A rectangle "is a" quadrilateral
Rectangle is a specific type of quadrilateral
Quadrilateral is the superclass, rectangle is the subclass
Incorrect to say quadrilateral "is a" rectangle
Naming can be confusing because subclass has more features than superclass
Subclass more specific than superclass
Every subclass "is an" object of its superclass, but not vice-versa
Form tree-like hierarchal structures
Create a hierarchy for class Shape (next slide)
11/20/2009
Võ Phương Bình - ITFAC - DLU
7
Superclasses and Subclasses, cont
Using inheritance
Use keyword extends
class TwoDimensionalShape extends Shape{ ... }
private members of superclass not directly accessible to subclass
All other variables keep their member access
11/20/2009
Võ Phương Bình - ITFAC - DLU
8
protected Members
In a superclass
public members
Accessible anywhere program has a reference to a superclass or subclass type
private members
Accessible only in methods of the superclass
protected members
Intermediate protection between private and public
Only accessible by methods of superclass, of subclass, or classes in the same package
Subclass methods
Can refer to public or protected members by name
Overridden methods accessible with super.methodName
11/20/2009
Võ Phương Bình - ITFAC - DLU
9
Relationship between Superclass Objects and Subclass Objects
Object of subclass
Can be treated as object of superclass
Reverse not true
Suppose many classes inherit from one superclass
Can make an array of superclass references
Treat all objects like superclass objects
Explicit cast
Convert superclass reference to a subclass reference (downcasting)
Can only be done when superclass reference actually referring to a subclass object
instanceof operator
if (p instanceof Circle)
Returns true if the object to which p points "is a" Circle
11/20/2009
Võ Phương Bình - ITFAC - DLU
10
Relationship between Superclass Objects and Subclass Objects, cont
Overriding methods
Subclass can redefine superclass method
When method mentioned in subclass, subclass version used
Access original superclass method with super.methodName
To invoke superclass constructor explicitly (called implicitly by default)
super(); //can pass arguments if needed
If called explicitly, must be first statement
Every Applet has used these techniques
Inheritance concept formalized
Java implicitly uses class Object as superclass for all classes
We have overridden init and paint when we extended JApplet
11/20/2009
Võ Phương Bình - ITFAC - DLU
11
11/20/2009
Võ Phương Bình - ITFAC - DLU
12
1.2 Methods
----------------
1. Circle Definition
1.1 extends Point
1.2 Multiple constructors
11/20/2009
Võ Phương Bình - ITFAC - DLU
13
11/20/2009
Võ Phương Bình - ITFAC - DLU
14
11/20/2009
Võ Phương Bình - ITFAC - DLU
15
11/20/2009
Võ Phương Bình - ITFAC - DLU
16
Program Output
11/20/2009
Võ Phương Bình - ITFAC - DLU
17
Implicit Subclass-Object-to-Superclass-Object Conversion
References to subclass objects
May be implicitly converted to superclass references
Makes sense - subclass contains members corresponding to those of superclass
Referring to a subclass object with a superclass reference
Allowed - a subclass object "is a" superclass object
Can only refer to superclass members
Referring to a superclass object with a subclass reference
Error
Must first be cast to a superclass reference
Need way to use superclass references but call subclass methods
Discussed later in the chapter
11/20/2009
Võ Phương Bình - ITFAC - DLU
18
Composition vs. Inheritance
"is a" relationship
Inheritance
"has a" relationship
Composition, having other objects as members
Example
Employee “is a” BirthDate; //Wrong!
Employee “has a” Birthdate; //Composition
11/20/2009
Võ Phương Bình - ITFAC - DLU
19
Introduction to Polymorphism
With polymorphism
Write extensible programs
Generically process superclass objects
Easy to add classes to hierarchy
Little or no modification required
Only parts of program that need direct knowledge of new class must be changed
11/20/2009
Võ Phương Bình - ITFAC - DLU
20
Dynamic Method Binding
Dynamic Method Binding
At execution time, method calls routed to appropriate version
Method called for appropriate class
Example
Triangle, Circle, and Square all subclasses of Shape
Each has an overridden draw method
Call draw using superclass references
At execution time, program determines to which class the reference is actually pointing
Calls appropriate draw method
11/20/2009
Võ Phương Bình - ITFAC - DLU
21
final Methods and Classes
Declaring variables final
Indicates they cannot be modified after declaration
Must be initialized when declared
Declaring methods final
Cannot be overridden in a subclass
static and private methods are implicitly final
Program can inline final methods
Actually inserts method code at method call locations
Improves program performance
Declaring classes final
Cannot be a superclass (cannot inherit from it)
All methods in class are implicitly final
11/20/2009
Võ Phương Bình - ITFAC - DLU
22
Abstract Superclasses and Concrete Classes
Abstract classes (abstract superclasses)
Sole purpose is to be a superclass
Other classes inherit from it
Cannot instantiate objects of an abstract class
Can still define constructor
Too generic to define real objects
Declare class with keyword abstract
Concrete class
Can instantiate objects
Provide specifics
Class hierarchies
Most general classes are usually abstract
TwoDimensionalShape - too generic to be concrete
11/20/2009
Võ Phương Bình - ITFAC - DLU
23
Polymorphism Example
Class Quadrilateral
Rectangle "is a" Quadrilateral
getPerimeter method can be performed on any subclass
Square, Parallelogram, Trapezoid
Same method takes on "many forms" - polymorphism
Have an array of superclass references
Array would point to all the objects
Call getPerimeter using the references
Appropriate method called for each class
Adding a new subclass
Simply need to define getPerimeter for that class
Can refer to it with superclass reference
Can use same superclass array as before - "fits right in"
11/20/2009
Võ Phương Bình - ITFAC - DLU
24
Polymorphism Example, cont
With polymorphism
New classes can be added easily
One method call can cause different actions to occur, depending on object receiving call
References
Can create references to abstract classes
Cannot instantiate objects of abstract classes
abstract methods
Keyword abstract
Any class with an abstract method must be abstract
abstract methods must be overridden in subclass
Otherwise, subclass must be abstract
11/20/2009
Võ Phương Bình - ITFAC - DLU
25
Polymorphism Example, cont
Iterator classes
Walks through all the objects in a container (such as an array)
Used in polymorphic programming
Walk through an array of superclass references
Call draw method for each reference
11/20/2009
Võ Phương Bình - ITFAC - DLU
26
New Classes and Dynamic Binding
Dynamic binding (late binding)
Accommodates new classes
Object`s type does not need to be known at compile time
At execution time, method call matched with object
11/20/2009
Võ Phương Bình - ITFAC - DLU
27
Inheriting Interface and Implementation
Polymorphism example
abstract superclass Shape
Subclasses Point, Circle, Cylinder
abstract method
getName
non-abstract methods
area (return 0.0)
volume (return 0.0)
Class Shape used to define a set of common methods
Interface is the three common methods
Implementation of area and volume used for first levels of hierarchy
Create an array of Shape references
Point them to various subclass objects
Call methods through the Shape reference
11/20/2009
Võ Phương Bình - ITFAC - DLU
28
11/20/2009
Võ Phương Bình - ITFAC - DLU
29
Class Point
1. point inherits from Shape
1.1 protected data members
1.2 Constructors
1.3 New methods
1.4 Overridden method getName
11/20/2009
Võ Phương Bình - ITFAC - DLU
30
Class Circle
1. Inherits from point
1.1 protected data member
1.2 Constructors
1.3 New methods
1.4 Overridden method area
11/20/2009
Võ Phương Bình - ITFAC - DLU
31
11/20/2009
Võ Phương Bình - ITFAC - DLU
32
Class Cylinder
1. inherit from Circle
1.1 protected data member
1.2 Constructors
1.3 New methods
1.4 Overridden method area
11/20/2009
Võ Phương Bình - ITFAC - DLU
33
11/20/2009
Võ Phương Bình - ITFAC - DLU
34
Driver
1. import
1.1 Initialize objects
1.2 Create Shape array
1.3 Initialize array
2. Call methods using objects
11/20/2009
Võ Phương Bình - ITFAC - DLU
35
2.1 Call methods using array of references
11/20/2009
Võ Phương Bình - ITFAC - DLU
36
Program Output
11/20/2009
Võ Phương Bình - ITFAC - DLU
37
Creating and Using Interfaces
Interface
Keyword interface
Has set of public abstract methods
Can contain public final static data
Using interfaces
Class specifies it uses interface with keyword implements
Multiple interfaces use comma-separated list
Class must define all abstract methods in interface
Must use same number of arguments, same return type
Using interface like signing a contract
"I will define all methods specified in the interface"
Same "is a" relationship as inheritance
11/20/2009
Võ Phương Bình - ITFAC - DLU
38
Creating and Using Interfaces, cont
Using interfaces (continued)
Interfaces used in place of abstract classes
Used when no default implementation
Typically public data types
Interface defined in its own .java file
Interface name same as file name
Previous interfaces
We have used interface ActionListener
Required to define actionPerformed
Reexamine previous hierarchy
Replace abstract class Shape with interface Shape
11/20/2009
Võ Phương Bình - ITFAC - DLU
39
11/20/2009
Võ Phương Bình - ITFAC - DLU
40
Class Point
1. inherits from Object
1.1 implements Shape
1.2 protected data members
1.3 Constructors
1.4 New methods
1.5 Define method area (required)
11/20/2009
Võ Phương Bình - ITFAC - DLU
41
11/20/2009
Võ Phương Bình - ITFAC - DLU
42
Class Circle
1. Inherits from Point
Define class Circle as before
11/20/2009
Võ Phương Bình - ITFAC - DLU
43
11/20/2009
Võ Phương Bình - ITFAC - DLU
44
Class Cylinder
1. Inherit from Circle
Define class Cylinder as before
11/20/2009
Võ Phương Bình - ITFAC - DLU
45
11/20/2009
Võ Phương Bình - ITFAC - DLU
46
Use same Driver as before
11/20/2009
Võ Phương Bình - ITFAC - DLU
47
Use same Driver as before
11/20/2009
Võ Phương Bình - ITFAC - DLU
48
Program Output (same as before)
11/20/2009
Võ Phương Bình - ITFAC - DLU
49
Inner Class Definitions
Inner classes
Till now, all classes defined at file scope (not inside other classes)
Inner classes defined inside other classes
Can access all members of outer class
No special handles needed
Anonymous inner class
Has no name
Frequently used with event handling
11/20/2009
Võ Phương Bình - ITFAC - DLU
50
Inner Class Definitions, cont
Windowed applications
We will execute an application in its own window (like an Applet)
Inherit from class JFrame (javax.swing) rather than JApplet
init method replaced by constructor
init not guaranteed to be called (only called for Applets)
Instead, create GUI components in constructor
Instantiate object in main (guaranteed to be called)
11/20/2009
Võ Phương Bình - ITFAC - DLU
51
Inner Class Definitions, cont
Event handling
Some class must implement interface ActionListener
Must define method actionPerformed
Class that implements ActionListener "is an" ActionListener
Method addActionListener
Takes object of type ActionListener
We can pass it an instance of the class that implements ActionListener ("is a" relationship)
Example
We will use the Time class and execute an application in its own window
Use event handling to set the time
11/20/2009
Võ Phương Bình - ITFAC - DLU
52
Time class
1. import
1.1 extends Object
1.2 Data members
1.3 Constructors
1.4 Member methods
11/20/2009
Võ Phương Bình - ITFAC - DLU
53
1.4 Member methods
11/20/2009
Võ Phương Bình - ITFAC - DLU
54
11/20/2009
Võ Phương Bình - ITFAC - DLU
55
11/20/2009
Võ Phương Bình - ITFAC - DLU
56
11/20/2009
Võ Phương Bình - ITFAC - DLU
57
Program Output
11/20/2009
Võ Phương Bình - ITFAC - DLU
58
Inner Class Definitions, cont
Event handling with anonymous Inner classes
Define the inner class inside the call to addActionListener
Create an instance of the class inside the method call
addActionListener takes an object of class ActionListener
11/20/2009
Võ Phương Bình - ITFAC - DLU
59
Inner Class Definitions, cont
Example
myField.addActionListener(
new ActionListener() { // anonymous inner class
public void actionPerformed( ActionEvent e)
{
Actions
}
}
);
11/20/2009
Võ Phương Bình - ITFAC - DLU
60
Inner Class Definitions, cont
New creates an object
ActionListener() begins definition of anonymous class and calls default constructor
Similar to public class myHandler implements ActionListener
Brace ( { ) begins class definition
11/20/2009
Võ Phương Bình - ITFAC - DLU
61
Inner Class Definitions, cont
Use the following code to allow the user to close windows using the close button
window.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
11/20/2009
Võ Phương Bình - ITFAC - DLU
62
Notes on Inner Class Definitions
Notes
Every class (including inner classes) have their own .class file
Named inner classes can be public, protected, private, or have package access
Same restrictions as other members of a class
To access outer class`s this reference
OuterClassName.this
11/20/2009
Võ Phương Bình - ITFAC - DLU
63
Notes on Inner Class Definitions, cont
Notes (continued)
To create an object of another class`s inner class
Create an object of outer class and assign it a reference (ref)
Type statement of form:
OuterClassName.InnerClassName innerRef = ref.new InnerClassName();
Inner class can be static
Does not require object of outer class to be defined
Does not have access to outer class`s non-static members
11/20/2009
Võ Phương Bình - ITFAC - DLU
64
Java API and Core Java classes
java.lang
Contains core Java classes, such as numeric classes, strings, and objects. This package is implicitly imported to every Java program.
java.awt
Contains classes for graphics.
java.applet
Contains classes for supporting applets.
11/20/2009
Võ Phương Bình - ITFAC - DLU
65
java.io
Contains classes for input and output
streams and files.
java.util
Contains many utilities, such as date.
java.net
Contains classes for supporting
network communications.
Java API and Core Java classes, cont.
11/20/2009
Võ Phương Bình - ITFAC - DLU
66
java.awt.image
Contains classes for managing bitmap images.
java.awt.peer
Platform-specific GUI implementation.
Others:
java.sql
java.rmi
Java API and Core Java classes, cont.
11/20/2009
Võ Phương Bình - ITFAC - DLU
67
Chapter 7: Strings
To process strings using the String class, the StringBuffer class, and the StringTokenizer class.
To use the String class to process fixed strings.
To use static methods in the Character class.
To use the StringBuffer class to process flexible strings.
To use the StringTokenizer class to extract tokens from a string.
To use the command-line arguments.
11/20/2009
Võ Phương Bình - ITFAC - DLU
68
The String Class
Constructing a String:
String message = "Welcome to Java!"
String message = new String("Welcome to Java!“);
String s = new String();
Obtaining String length and Retrieving Individual Characters in a string String
String Concatenation (concat)
Substrings (substring(index), substring(start, end))
Comparisons (equals, compareTo)
String Conversions
Finding a Character or a Substring in a String
Conversions between Strings and Arrays
Converting Characters and Numeric Values to Strings
11/20/2009
Võ Phương Bình - ITFAC - DLU
69
11/20/2009
Võ Phương Bình - ITFAC - DLU
70
Constructing Strings
Strings newString = new String(stringLiteral);
String message = new String("Welcome to Java!");
Since strings are used frequently, Java provides a shorthand notation for creating a string:
String message = "Welcome to Java!";
11/20/2009
Võ Phương Bình - ITFAC - DLU
71
Strings Are Immutable
NOTE:
A String object is immutable, whose contents cannot be changed.
To improve efficiency and save memory, Java Virtual Machine stores two String objects into the same object, if the two String objects are created with the same string literal using the shorthand notation.
Therefore, the shorthand notation is preferred to create strings.
11/20/2009
Võ Phương Bình - ITFAC - DLU
72
Strings Are Immutable, cont.
NOTE:
A string that is created using the shorthand notation is known as a canonical string.
You can use the String’s intern method to return a canonical string, which is the same string that is created using the shorthand notation.
11/20/2009
Võ Phương Bình - ITFAC - DLU
73
Examples
String s = "Welcome to Java!";
String s1 = new String("Welcome to Java!");
String s2 = s1.intern();
System.out.println("s1 == s is " + (s1 == s));
System.out.println("s2 == s is " + (s2 == s));
System.out.println("s1 == s2 is " + (s1 == s2));
display
s1 == s is false
s2 == s is true
s1 == s2 false
11/20/2009
Võ Phương Bình - ITFAC - DLU
74
Finding String Length
Finding string length using the length() method:
message = "Welcome";
message.length() (returns 7)
11/20/2009
Võ Phương Bình - ITFAC - DLU
75
Retrieving Individual Characters in a String
Do not use message[0]
Use message.charAt(index)
Index starts from 0
11/20/2009
Võ Phương Bình - ITFAC - DLU
76
String Concatenation
String s3 = s1.concat(s2);
String s3 = s1 + s2;
11/20/2009
Võ Phương Bình - ITFAC - DLU
77
Extracting Substrings
String is an immutable class; its values
cannot be changed individually.
String s1 = "Welcome to Java";
String s2 = s1.substring(0, 11) + "HTML";
11/20/2009
Võ Phương Bình - ITFAC - DLU
78
String Comparisons
equals
String s1 = "Welcome";
String s2 = "welcome";
if (s1.equals(s2)){
// s1 and s2 have the same contents
}
if (s1 == s2) {
// s1 and s2 have the same reference
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
79
String Comparisons, cont.
compareTo(Object object)
String s1 = "Welcome";
String s2 = "welcome";
if (s1.compareTo(s2) > 0) {
// s1 is greater than s2
}
else if (s1.compareTo(s2 == 0) {
// s1 and s2 have the same reference
}
else
// s1 is less than s2
11/20/2009
Võ Phương Bình - ITFAC - DLU
80
String Conversions
The contents of a string cannot be changed once the string is created. But you can convert a string to a new string using the following methods:
toLowerCase
toUpperCase
trim
replace(oldChar, newChar)
11/20/2009
Võ Phương Bình - ITFAC - DLU
81
Finding a Character or a Substring in a String
"Welcome to Java!".indexOf(`W`)) returns 0.
"Welcome to Java!".indexOf(`x`)) returns -1.
"Welcome to Java!".indexOf(`o`, 5)) returns 9.
"Welcome to Java!".indexOf("come")) returns 3.
"Welcome to Java!".indexOf("Java", 5)) returns 11.
"Welcome to Java!".indexOf("java", 5)) returns -1.
11/20/2009
Võ Phương Bình - ITFAC - DLU
82
Convert Character and Numbers to Strings
The String class provides several static valueOf methods for converting a character, an array of characters, and numeric values to strings.
These methods have the same name valueOf with different argument types char, char[], double, long, int, and float.
For example, to convert a double value to a string, use String.valueOf(5.44). The return value is string consists of characters ‘5’, ‘.’, ‘4’, and ‘4’.
11/20/2009
Võ Phương Bình - ITFAC - DLU
83
The Character Class
11/20/2009
Võ Phương Bình - ITFAC - DLU
84
Examples
charObject.compareTo(new Character(`a`)) returns 1
charObject.compareTo(new Character(`b`)) returns 0
charObject.compareTo(new Character(`c`)) returns -1
charObject.compareTo(new Character(`d`) returns –2
charObject.equals(new Character(`b`)) returns true
charObject.equals(new Character(`d`)) returns false
11/20/2009
Võ Phương Bình - ITFAC - DLU
85
The StringBuffer Class
The StringBuffer class is an alternative to the String class. In general, a string buffer can be used wherever a string is used.
StringBuffer is more flexible than String. You can add, insert, or append new contents into a string buffer.
However, the value of a string is fixed once the string is created.
11/20/2009
Võ Phương Bình - ITFAC - DLU
86
11/20/2009
Võ Phương Bình - ITFAC - DLU
87
StringBuffer Constructors
public StringBuffer()
No characters, initial capacity 16 characters.
public StringBuffer(int length)
No characters, initial capacity specified by the length argument.
public StringBuffer(String str)
Represents the same sequence of characters
as the string argument. Initial capacity 16
plus the length of the string argument.
11/20/2009
Võ Phương Bình - ITFAC - DLU
88
Appending New Contents
into a String Buffer
StringBuffer strBuf = new StringBuffer();
strBuf.append("Welcome");
strBuf.append(` `);
strBuf.append("to");
strBuf.append(` `);
strBuf.append("Java");
11/20/2009
Võ Phương Bình - ITFAC - DLU
89
The StringTokenizer Class Constructors
StringTokenizer(String s, String delim, boolean returnTokens)
StringTokenizer(String s, String delim)
StringTokenizer(String s)
11/20/2009
Võ Phương Bình - ITFAC - DLU
90
The StringTokenizer Class Methods
boolean hasMoreTokens()
String nextToken()
String nextToken(String delim)
11/20/2009
Võ Phương Bình - ITFAC - DLU
91
Command-Line Parameters
class TestMain {
public static void main(String[] args) {
...
}
}
java TestMain arg0 arg1 arg2 ... argn
11/20/2009
Võ Phương Bình - ITFAC - DLU
92
Processing
Command-Line Parameters
In the main method, get the arguments from args[0], args[1], ..., args[n], which corresponds to arg0, arg1, ..., argn in the command line.
Võ Phương Bình - ITFAC - DLU
1
Part II: Object-Oriented Programming
Chapter 6: Object-Oriented Programming
Chapter 7: Strings
11/20/2009
Võ Phương Bình - ITFAC - DLU
2
Chapter 6: Object-Oriented Programming
Introduction
Superclasses and Subclasses
protected Members
Relationship between Superclass Objects and Subclass Objects
Implicit Subclass-Object-to-Superclass-Object Conversion
Composition vs. Inheritance
Introduction to Polymorphism
11/20/2009
Võ Phương Bình - ITFAC - DLU
3
Chapter 6: Object-Oriented Programming
Dynamic Method Binding
final Methods and Classes
Abstract Superclasses and Concrete Classes
Polymorphism Example
New Classes and Dynamic Binding
Inheriting Interface and Implementation
Creating and Using Interfaces
Inner Class Definitions
Notes on Inner Class Definitions
11/20/2009
Võ Phương Bình - ITFAC - DLU
4
Introduction
Object-Oriented Programming (OOP)
Inheritance - form of software reusability
New classes created from existing ones
Absorb attributes and behaviors, and add in their own
Override methods - redefine inherited methods
Subclass inherits from superclass
Direct superclass - subclass explicitly inherits
Indirect superclass - subclass inherits from two or more levels up the class hierarchy
Polymorphism
Write programs in a general fashion to handle a wide variety of classes
Abstraction - seeing the big picture
11/20/2009
Võ Phương Bình - ITFAC - DLU
5
Introduction, cont
Object-Oriented Programming
Introduce protected member access
Relationships
"is a" - inheritance
Object of subclass "is a" object of the superclass
"has a" - composition
Object "has a" object of another class as a member
Class libraries
New classes can inherit from them
Someday software may be constructed from standardized, reusable components (like hardware)
Create more powerful software
11/20/2009
Võ Phương Bình - ITFAC - DLU
6
Superclasses and Subclasses
Inheritance example
A rectangle "is a" quadrilateral
Rectangle is a specific type of quadrilateral
Quadrilateral is the superclass, rectangle is the subclass
Incorrect to say quadrilateral "is a" rectangle
Naming can be confusing because subclass has more features than superclass
Subclass more specific than superclass
Every subclass "is an" object of its superclass, but not vice-versa
Form tree-like hierarchal structures
Create a hierarchy for class Shape (next slide)
11/20/2009
Võ Phương Bình - ITFAC - DLU
7
Superclasses and Subclasses, cont
Using inheritance
Use keyword extends
class TwoDimensionalShape extends Shape{ ... }
private members of superclass not directly accessible to subclass
All other variables keep their member access
11/20/2009
Võ Phương Bình - ITFAC - DLU
8
protected Members
In a superclass
public members
Accessible anywhere program has a reference to a superclass or subclass type
private members
Accessible only in methods of the superclass
protected members
Intermediate protection between private and public
Only accessible by methods of superclass, of subclass, or classes in the same package
Subclass methods
Can refer to public or protected members by name
Overridden methods accessible with super.methodName
11/20/2009
Võ Phương Bình - ITFAC - DLU
9
Relationship between Superclass Objects and Subclass Objects
Object of subclass
Can be treated as object of superclass
Reverse not true
Suppose many classes inherit from one superclass
Can make an array of superclass references
Treat all objects like superclass objects
Explicit cast
Convert superclass reference to a subclass reference (downcasting)
Can only be done when superclass reference actually referring to a subclass object
instanceof operator
if (p instanceof Circle)
Returns true if the object to which p points "is a" Circle
11/20/2009
Võ Phương Bình - ITFAC - DLU
10
Relationship between Superclass Objects and Subclass Objects, cont
Overriding methods
Subclass can redefine superclass method
When method mentioned in subclass, subclass version used
Access original superclass method with super.methodName
To invoke superclass constructor explicitly (called implicitly by default)
super(); //can pass arguments if needed
If called explicitly, must be first statement
Every Applet has used these techniques
Inheritance concept formalized
Java implicitly uses class Object as superclass for all classes
We have overridden init and paint when we extended JApplet
11/20/2009
Võ Phương Bình - ITFAC - DLU
11
11/20/2009
Võ Phương Bình - ITFAC - DLU
12
1.2 Methods
----------------
1. Circle Definition
1.1 extends Point
1.2 Multiple constructors
11/20/2009
Võ Phương Bình - ITFAC - DLU
13
11/20/2009
Võ Phương Bình - ITFAC - DLU
14
11/20/2009
Võ Phương Bình - ITFAC - DLU
15
11/20/2009
Võ Phương Bình - ITFAC - DLU
16
Program Output
11/20/2009
Võ Phương Bình - ITFAC - DLU
17
Implicit Subclass-Object-to-Superclass-Object Conversion
References to subclass objects
May be implicitly converted to superclass references
Makes sense - subclass contains members corresponding to those of superclass
Referring to a subclass object with a superclass reference
Allowed - a subclass object "is a" superclass object
Can only refer to superclass members
Referring to a superclass object with a subclass reference
Error
Must first be cast to a superclass reference
Need way to use superclass references but call subclass methods
Discussed later in the chapter
11/20/2009
Võ Phương Bình - ITFAC - DLU
18
Composition vs. Inheritance
"is a" relationship
Inheritance
"has a" relationship
Composition, having other objects as members
Example
Employee “is a” BirthDate; //Wrong!
Employee “has a” Birthdate; //Composition
11/20/2009
Võ Phương Bình - ITFAC - DLU
19
Introduction to Polymorphism
With polymorphism
Write extensible programs
Generically process superclass objects
Easy to add classes to hierarchy
Little or no modification required
Only parts of program that need direct knowledge of new class must be changed
11/20/2009
Võ Phương Bình - ITFAC - DLU
20
Dynamic Method Binding
Dynamic Method Binding
At execution time, method calls routed to appropriate version
Method called for appropriate class
Example
Triangle, Circle, and Square all subclasses of Shape
Each has an overridden draw method
Call draw using superclass references
At execution time, program determines to which class the reference is actually pointing
Calls appropriate draw method
11/20/2009
Võ Phương Bình - ITFAC - DLU
21
final Methods and Classes
Declaring variables final
Indicates they cannot be modified after declaration
Must be initialized when declared
Declaring methods final
Cannot be overridden in a subclass
static and private methods are implicitly final
Program can inline final methods
Actually inserts method code at method call locations
Improves program performance
Declaring classes final
Cannot be a superclass (cannot inherit from it)
All methods in class are implicitly final
11/20/2009
Võ Phương Bình - ITFAC - DLU
22
Abstract Superclasses and Concrete Classes
Abstract classes (abstract superclasses)
Sole purpose is to be a superclass
Other classes inherit from it
Cannot instantiate objects of an abstract class
Can still define constructor
Too generic to define real objects
Declare class with keyword abstract
Concrete class
Can instantiate objects
Provide specifics
Class hierarchies
Most general classes are usually abstract
TwoDimensionalShape - too generic to be concrete
11/20/2009
Võ Phương Bình - ITFAC - DLU
23
Polymorphism Example
Class Quadrilateral
Rectangle "is a" Quadrilateral
getPerimeter method can be performed on any subclass
Square, Parallelogram, Trapezoid
Same method takes on "many forms" - polymorphism
Have an array of superclass references
Array would point to all the objects
Call getPerimeter using the references
Appropriate method called for each class
Adding a new subclass
Simply need to define getPerimeter for that class
Can refer to it with superclass reference
Can use same superclass array as before - "fits right in"
11/20/2009
Võ Phương Bình - ITFAC - DLU
24
Polymorphism Example, cont
With polymorphism
New classes can be added easily
One method call can cause different actions to occur, depending on object receiving call
References
Can create references to abstract classes
Cannot instantiate objects of abstract classes
abstract methods
Keyword abstract
Any class with an abstract method must be abstract
abstract methods must be overridden in subclass
Otherwise, subclass must be abstract
11/20/2009
Võ Phương Bình - ITFAC - DLU
25
Polymorphism Example, cont
Iterator classes
Walks through all the objects in a container (such as an array)
Used in polymorphic programming
Walk through an array of superclass references
Call draw method for each reference
11/20/2009
Võ Phương Bình - ITFAC - DLU
26
New Classes and Dynamic Binding
Dynamic binding (late binding)
Accommodates new classes
Object`s type does not need to be known at compile time
At execution time, method call matched with object
11/20/2009
Võ Phương Bình - ITFAC - DLU
27
Inheriting Interface and Implementation
Polymorphism example
abstract superclass Shape
Subclasses Point, Circle, Cylinder
abstract method
getName
non-abstract methods
area (return 0.0)
volume (return 0.0)
Class Shape used to define a set of common methods
Interface is the three common methods
Implementation of area and volume used for first levels of hierarchy
Create an array of Shape references
Point them to various subclass objects
Call methods through the Shape reference
11/20/2009
Võ Phương Bình - ITFAC - DLU
28
11/20/2009
Võ Phương Bình - ITFAC - DLU
29
Class Point
1. point inherits from Shape
1.1 protected data members
1.2 Constructors
1.3 New methods
1.4 Overridden method getName
11/20/2009
Võ Phương Bình - ITFAC - DLU
30
Class Circle
1. Inherits from point
1.1 protected data member
1.2 Constructors
1.3 New methods
1.4 Overridden method area
11/20/2009
Võ Phương Bình - ITFAC - DLU
31
11/20/2009
Võ Phương Bình - ITFAC - DLU
32
Class Cylinder
1. inherit from Circle
1.1 protected data member
1.2 Constructors
1.3 New methods
1.4 Overridden method area
11/20/2009
Võ Phương Bình - ITFAC - DLU
33
11/20/2009
Võ Phương Bình - ITFAC - DLU
34
Driver
1. import
1.1 Initialize objects
1.2 Create Shape array
1.3 Initialize array
2. Call methods using objects
11/20/2009
Võ Phương Bình - ITFAC - DLU
35
2.1 Call methods using array of references
11/20/2009
Võ Phương Bình - ITFAC - DLU
36
Program Output
11/20/2009
Võ Phương Bình - ITFAC - DLU
37
Creating and Using Interfaces
Interface
Keyword interface
Has set of public abstract methods
Can contain public final static data
Using interfaces
Class specifies it uses interface with keyword implements
Multiple interfaces use comma-separated list
Class must define all abstract methods in interface
Must use same number of arguments, same return type
Using interface like signing a contract
"I will define all methods specified in the interface"
Same "is a" relationship as inheritance
11/20/2009
Võ Phương Bình - ITFAC - DLU
38
Creating and Using Interfaces, cont
Using interfaces (continued)
Interfaces used in place of abstract classes
Used when no default implementation
Typically public data types
Interface defined in its own .java file
Interface name same as file name
Previous interfaces
We have used interface ActionListener
Required to define actionPerformed
Reexamine previous hierarchy
Replace abstract class Shape with interface Shape
11/20/2009
Võ Phương Bình - ITFAC - DLU
39
11/20/2009
Võ Phương Bình - ITFAC - DLU
40
Class Point
1. inherits from Object
1.1 implements Shape
1.2 protected data members
1.3 Constructors
1.4 New methods
1.5 Define method area (required)
11/20/2009
Võ Phương Bình - ITFAC - DLU
41
11/20/2009
Võ Phương Bình - ITFAC - DLU
42
Class Circle
1. Inherits from Point
Define class Circle as before
11/20/2009
Võ Phương Bình - ITFAC - DLU
43
11/20/2009
Võ Phương Bình - ITFAC - DLU
44
Class Cylinder
1. Inherit from Circle
Define class Cylinder as before
11/20/2009
Võ Phương Bình - ITFAC - DLU
45
11/20/2009
Võ Phương Bình - ITFAC - DLU
46
Use same Driver as before
11/20/2009
Võ Phương Bình - ITFAC - DLU
47
Use same Driver as before
11/20/2009
Võ Phương Bình - ITFAC - DLU
48
Program Output (same as before)
11/20/2009
Võ Phương Bình - ITFAC - DLU
49
Inner Class Definitions
Inner classes
Till now, all classes defined at file scope (not inside other classes)
Inner classes defined inside other classes
Can access all members of outer class
No special handles needed
Anonymous inner class
Has no name
Frequently used with event handling
11/20/2009
Võ Phương Bình - ITFAC - DLU
50
Inner Class Definitions, cont
Windowed applications
We will execute an application in its own window (like an Applet)
Inherit from class JFrame (javax.swing) rather than JApplet
init method replaced by constructor
init not guaranteed to be called (only called for Applets)
Instead, create GUI components in constructor
Instantiate object in main (guaranteed to be called)
11/20/2009
Võ Phương Bình - ITFAC - DLU
51
Inner Class Definitions, cont
Event handling
Some class must implement interface ActionListener
Must define method actionPerformed
Class that implements ActionListener "is an" ActionListener
Method addActionListener
Takes object of type ActionListener
We can pass it an instance of the class that implements ActionListener ("is a" relationship)
Example
We will use the Time class and execute an application in its own window
Use event handling to set the time
11/20/2009
Võ Phương Bình - ITFAC - DLU
52
Time class
1. import
1.1 extends Object
1.2 Data members
1.3 Constructors
1.4 Member methods
11/20/2009
Võ Phương Bình - ITFAC - DLU
53
1.4 Member methods
11/20/2009
Võ Phương Bình - ITFAC - DLU
54
11/20/2009
Võ Phương Bình - ITFAC - DLU
55
11/20/2009
Võ Phương Bình - ITFAC - DLU
56
11/20/2009
Võ Phương Bình - ITFAC - DLU
57
Program Output
11/20/2009
Võ Phương Bình - ITFAC - DLU
58
Inner Class Definitions, cont
Event handling with anonymous Inner classes
Define the inner class inside the call to addActionListener
Create an instance of the class inside the method call
addActionListener takes an object of class ActionListener
11/20/2009
Võ Phương Bình - ITFAC - DLU
59
Inner Class Definitions, cont
Example
myField.addActionListener(
new ActionListener() { // anonymous inner class
public void actionPerformed( ActionEvent e)
{
Actions
}
}
);
11/20/2009
Võ Phương Bình - ITFAC - DLU
60
Inner Class Definitions, cont
New creates an object
ActionListener() begins definition of anonymous class and calls default constructor
Similar to public class myHandler implements ActionListener
Brace ( { ) begins class definition
11/20/2009
Võ Phương Bình - ITFAC - DLU
61
Inner Class Definitions, cont
Use the following code to allow the user to close windows using the close button
window.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
11/20/2009
Võ Phương Bình - ITFAC - DLU
62
Notes on Inner Class Definitions
Notes
Every class (including inner classes) have their own .class file
Named inner classes can be public, protected, private, or have package access
Same restrictions as other members of a class
To access outer class`s this reference
OuterClassName.this
11/20/2009
Võ Phương Bình - ITFAC - DLU
63
Notes on Inner Class Definitions, cont
Notes (continued)
To create an object of another class`s inner class
Create an object of outer class and assign it a reference (ref)
Type statement of form:
OuterClassName.InnerClassName innerRef = ref.new InnerClassName();
Inner class can be static
Does not require object of outer class to be defined
Does not have access to outer class`s non-static members
11/20/2009
Võ Phương Bình - ITFAC - DLU
64
Java API and Core Java classes
java.lang
Contains core Java classes, such as numeric classes, strings, and objects. This package is implicitly imported to every Java program.
java.awt
Contains classes for graphics.
java.applet
Contains classes for supporting applets.
11/20/2009
Võ Phương Bình - ITFAC - DLU
65
java.io
Contains classes for input and output
streams and files.
java.util
Contains many utilities, such as date.
java.net
Contains classes for supporting
network communications.
Java API and Core Java classes, cont.
11/20/2009
Võ Phương Bình - ITFAC - DLU
66
java.awt.image
Contains classes for managing bitmap images.
java.awt.peer
Platform-specific GUI implementation.
Others:
java.sql
java.rmi
Java API and Core Java classes, cont.
11/20/2009
Võ Phương Bình - ITFAC - DLU
67
Chapter 7: Strings
To process strings using the String class, the StringBuffer class, and the StringTokenizer class.
To use the String class to process fixed strings.
To use static methods in the Character class.
To use the StringBuffer class to process flexible strings.
To use the StringTokenizer class to extract tokens from a string.
To use the command-line arguments.
11/20/2009
Võ Phương Bình - ITFAC - DLU
68
The String Class
Constructing a String:
String message = "Welcome to Java!"
String message = new String("Welcome to Java!“);
String s = new String();
Obtaining String length and Retrieving Individual Characters in a string String
String Concatenation (concat)
Substrings (substring(index), substring(start, end))
Comparisons (equals, compareTo)
String Conversions
Finding a Character or a Substring in a String
Conversions between Strings and Arrays
Converting Characters and Numeric Values to Strings
11/20/2009
Võ Phương Bình - ITFAC - DLU
69
11/20/2009
Võ Phương Bình - ITFAC - DLU
70
Constructing Strings
Strings newString = new String(stringLiteral);
String message = new String("Welcome to Java!");
Since strings are used frequently, Java provides a shorthand notation for creating a string:
String message = "Welcome to Java!";
11/20/2009
Võ Phương Bình - ITFAC - DLU
71
Strings Are Immutable
NOTE:
A String object is immutable, whose contents cannot be changed.
To improve efficiency and save memory, Java Virtual Machine stores two String objects into the same object, if the two String objects are created with the same string literal using the shorthand notation.
Therefore, the shorthand notation is preferred to create strings.
11/20/2009
Võ Phương Bình - ITFAC - DLU
72
Strings Are Immutable, cont.
NOTE:
A string that is created using the shorthand notation is known as a canonical string.
You can use the String’s intern method to return a canonical string, which is the same string that is created using the shorthand notation.
11/20/2009
Võ Phương Bình - ITFAC - DLU
73
Examples
String s = "Welcome to Java!";
String s1 = new String("Welcome to Java!");
String s2 = s1.intern();
System.out.println("s1 == s is " + (s1 == s));
System.out.println("s2 == s is " + (s2 == s));
System.out.println("s1 == s2 is " + (s1 == s2));
display
s1 == s is false
s2 == s is true
s1 == s2 false
11/20/2009
Võ Phương Bình - ITFAC - DLU
74
Finding String Length
Finding string length using the length() method:
message = "Welcome";
message.length() (returns 7)
11/20/2009
Võ Phương Bình - ITFAC - DLU
75
Retrieving Individual Characters in a String
Do not use message[0]
Use message.charAt(index)
Index starts from 0
11/20/2009
Võ Phương Bình - ITFAC - DLU
76
String Concatenation
String s3 = s1.concat(s2);
String s3 = s1 + s2;
11/20/2009
Võ Phương Bình - ITFAC - DLU
77
Extracting Substrings
String is an immutable class; its values
cannot be changed individually.
String s1 = "Welcome to Java";
String s2 = s1.substring(0, 11) + "HTML";
11/20/2009
Võ Phương Bình - ITFAC - DLU
78
String Comparisons
equals
String s1 = "Welcome";
String s2 = "welcome";
if (s1.equals(s2)){
// s1 and s2 have the same contents
}
if (s1 == s2) {
// s1 and s2 have the same reference
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
79
String Comparisons, cont.
compareTo(Object object)
String s1 = "Welcome";
String s2 = "welcome";
if (s1.compareTo(s2) > 0) {
// s1 is greater than s2
}
else if (s1.compareTo(s2 == 0) {
// s1 and s2 have the same reference
}
else
// s1 is less than s2
11/20/2009
Võ Phương Bình - ITFAC - DLU
80
String Conversions
The contents of a string cannot be changed once the string is created. But you can convert a string to a new string using the following methods:
toLowerCase
toUpperCase
trim
replace(oldChar, newChar)
11/20/2009
Võ Phương Bình - ITFAC - DLU
81
Finding a Character or a Substring in a String
"Welcome to Java!".indexOf(`W`)) returns 0.
"Welcome to Java!".indexOf(`x`)) returns -1.
"Welcome to Java!".indexOf(`o`, 5)) returns 9.
"Welcome to Java!".indexOf("come")) returns 3.
"Welcome to Java!".indexOf("Java", 5)) returns 11.
"Welcome to Java!".indexOf("java", 5)) returns -1.
11/20/2009
Võ Phương Bình - ITFAC - DLU
82
Convert Character and Numbers to Strings
The String class provides several static valueOf methods for converting a character, an array of characters, and numeric values to strings.
These methods have the same name valueOf with different argument types char, char[], double, long, int, and float.
For example, to convert a double value to a string, use String.valueOf(5.44). The return value is string consists of characters ‘5’, ‘.’, ‘4’, and ‘4’.
11/20/2009
Võ Phương Bình - ITFAC - DLU
83
The Character Class
11/20/2009
Võ Phương Bình - ITFAC - DLU
84
Examples
charObject.compareTo(new Character(`a`)) returns 1
charObject.compareTo(new Character(`b`)) returns 0
charObject.compareTo(new Character(`c`)) returns -1
charObject.compareTo(new Character(`d`) returns –2
charObject.equals(new Character(`b`)) returns true
charObject.equals(new Character(`d`)) returns false
11/20/2009
Võ Phương Bình - ITFAC - DLU
85
The StringBuffer Class
The StringBuffer class is an alternative to the String class. In general, a string buffer can be used wherever a string is used.
StringBuffer is more flexible than String. You can add, insert, or append new contents into a string buffer.
However, the value of a string is fixed once the string is created.
11/20/2009
Võ Phương Bình - ITFAC - DLU
86
11/20/2009
Võ Phương Bình - ITFAC - DLU
87
StringBuffer Constructors
public StringBuffer()
No characters, initial capacity 16 characters.
public StringBuffer(int length)
No characters, initial capacity specified by the length argument.
public StringBuffer(String str)
Represents the same sequence of characters
as the string argument. Initial capacity 16
plus the length of the string argument.
11/20/2009
Võ Phương Bình - ITFAC - DLU
88
Appending New Contents
into a String Buffer
StringBuffer strBuf = new StringBuffer();
strBuf.append("Welcome");
strBuf.append(` `);
strBuf.append("to");
strBuf.append(` `);
strBuf.append("Java");
11/20/2009
Võ Phương Bình - ITFAC - DLU
89
The StringTokenizer Class Constructors
StringTokenizer(String s, String delim, boolean returnTokens)
StringTokenizer(String s, String delim)
StringTokenizer(String s)
11/20/2009
Võ Phương Bình - ITFAC - DLU
90
The StringTokenizer Class Methods
boolean hasMoreTokens()
String nextToken()
String nextToken(String delim)
11/20/2009
Võ Phương Bình - ITFAC - DLU
91
Command-Line Parameters
class TestMain {
public static void main(String[] args) {
...
}
}
java TestMain arg0 arg1 arg2 ... argn
11/20/2009
Võ Phương Bình - ITFAC - DLU
92
Processing
Command-Line Parameters
In the main method, get the arguments from args[0], args[1], ..., args[n], which corresponds to arg0, arg1, ..., argn in the command line.
* Một số tài liệu cũ có thể bị lỗi font khi hiển thị do dùng bộ mã không phải Unikey ...
Người chia sẻ: Nguyễn Bùi Minh Tâm
Dung lượng: |
Lượt tài: 1
Loại file:
Nguồn : Chưa rõ
(Tài liệu chưa được thẩm định)