Date post: | 20-Jan-2016 |
Category: |
Documents |
Upload: | cameron-ellis |
View: | 226 times |
Download: | 1 times |
Chapter 5Programming with Objects and Classes
OO Programming ConceptsOO Programming Concepts Declaring and Creating ObjectsDeclaring and Creating Objects ConstructorsConstructors Modifiers (public, private and static)Modifiers (public, private and static) Instance and Class Variables and MethodsInstance and Class Variables and Methods Analyzing Relationships among ClassesAnalyzing Relationships among Classes Case Studies (Mortgage class and Rational class)Case Studies (Mortgage class and Rational class) The Java API and Core Java classesThe Java API and Core Java classes Processing StringsProcessing Strings
OO Programming Concepts
data field 1
method n
data field n
method 1
An object
...
...
States
Behaviors
Data Field radius = 5
Method findArea
A Circle object
Class and Objects
Circle
radius
findArea
circle1: Circle
radius = 2
new Circle()
circlen: Circle
radius = 5
new Circle()
...
Graphical notation for classes
Graphical notation for objects
Class Declaration
class Circle { class Circle {
// states// states double radius = 1.0;double radius = 1.0;
// // behaviorsbehaviors double findArea() {double findArea() { return radius*radius*3.14159; return radius*radius*3.14159; }}}}
Declaring Objects
ClassName objectName;ClassName objectName;
Example:Example:Circle myCircle;Circle myCircle;
Creating Objects
objectName = new ClassName();objectName = new ClassName();
Example:Example:myCircle = new Circle();myCircle = new Circle();
Declaring/Creating Objectsin a Single Step
ClassName objectName = new ClassName();ClassName objectName = new ClassName();
Example:Example:Circle myCircle = new Circle();Circle myCircle = new Circle();
Differences between variables of primitive types and object types
1
c: Circle
radius = 5
Primitive type int i = 1 i
Object type Circle c c
reference
Created using new Circle(5)
Copying Variables of Primitive Types and Object Types
1
c1: Circle
radius = 5
Primitive type assignment i = j
Before:
i
2 j
2
After:
i
2 j
Object type assignment c1 = c2
Before:
c1
c2
After:
c1
c2
c2: Circle
radius = 9
Accessing Objects
Referencing the object’s data:Referencing the object’s data:
objectName.dataobjectName.data
myCircle.radiusmyCircle.radius
Referencing the object’s method:Referencing the object’s method:
objectName.methodobjectName.method
myCircle.findArea()myCircle.findArea()
Example 5.1Using Objects
Objective: Demonstrate creating objects, Objective: Demonstrate creating objects, accessing data, and using methods. accessing data, and using methods.
TestCircleTestCircle RunRun
Constructors
Circle(double r) Circle(double r) { { radius = r;radius = r;}}
Circle() Circle() {{ radius = 1.0; radius = 1.0; }}
myCircle = new Circle(5.0);myCircle = new Circle(5.0);
Example 5.2Using Constructors
Objective: Discuss the role of constructors Objective: Discuss the role of constructors and use them to create objects.and use them to create objects.
TestCircleWithConstructorsTestCircleWithConstructors RunRun
Passing Objects to Methods
Passing by referencePassing by reference
Passing by valuePassing by value
Example 5.3 Passing Objects as Example 5.3 Passing Objects as ArgumentsArguments
TestPassingObjectTestPassingObject RunRun
Visibility Modifiers and Accessor MethodsBy default, the class, variable, or data can beBy default, the class, variable, or data can beaccessed by any class in the same package.accessed by any class in the same package.
publicThe class, data, or method is visible to any class in any package.
private The data or methods can be accessed only by the declaring class.
The getter and setter accessor methods are used to read and modify private properties.
Example 5.4Using the private Modifier and Accessor Methods
TestCircleWithPrivateModifierTestCircleWithPrivateModifier RunRun
In this example, private data are used for the radius and the accessor methods getRadius and setRadius are provided for the clients to retrieve and modify the radius.
Instance Variables, and Methods
Instance variables belong to a specific instance.
Instance methods are invoked by an instance of the class.
Class Variables, Constants, and Methods
Class variables are shared by all the instances of the class.
Class methods are not tied to a specific object.
Class constants are final variables shared by all the instances of the class.
To declare class variables, constants, and methods, use the static modifier.
Class Variables, Constants, and Methods, cont.
Circle
-radius-numOfObjects
+getRadius+setRadius+getNumOfObjects +findArea
1 radiuscircle1:Circle
-radius = 1-numOfObjects = 2
instantiate
instantiate
Memory
2
5 radius
numOfObjects
radius is an instancevariable, andnumOfObjects is aclass variable
Notation: +: public variables or methods -: private variables or methods underline: static variables or metods
circle2:Circle
-radius = 5-numOfObjects = 2
UML notation(Unified Modeling language)
Example 5.5Using Instance and Class Variables and Method
Objective: Demonstrate the roles of Objective: Demonstrate the roles of instance and class variables and instance and class variables and their uses. This example adds a their uses. This example adds a class variable class variable numOfObjectsnumOfObjects to track to track the number of the number of CircleCircle objects created. objects created.
TestInstanceAndClassVariableTestInstanceAndClassVariable RunRun
Analyzing Relationships among Classes
AssociationAssociation
AggregationAggregation
InheritanceInheritance
Association
AssociationAssociation represents a general represents a general
binary relationship that describes binary relationship that describes
an activity between two classes. an activity between two classes.
Student Faculty Course * 5..60 Take Teach 0..3 1
Teacher
Aggregation
AggregationAggregation is a special form of association, which is a special form of association, which
represents an ownership relationship between two represents an ownership relationship between two
classes. classes.
Aggregation models the relationship like has-a, Aggregation models the relationship like has-a,
part-of, owns, and employed-by.part-of, owns, and employed-by.
Magazine ConsultantPublisher1*
Owned by Employed by**
Expert
Inheritance
InheritanceInheritance models the is-a relationship models the is-a relationship
between two classes. between two classes.
Person
Faculty
Student
Class Abstraction
Class abstraction means to separate class Class abstraction means to separate class implementation from the use of the class.implementation from the use of the class.
The creator of the class provides a The creator of the class provides a description of the class and let the user description of the class and let the user know how the class can be used.know how the class can be used.
The user of the class does not need to The user of the class does not need to know how the class is implemented. know how the class is implemented.
The detail of implementation is The detail of implementation is encapsulated and hidden from the user. encapsulated and hidden from the user.
Class Design
1. 1. Identify classes for the system.Identify classes for the system.
2. Describe attributes and methods in 2. Describe attributes and methods in
each class.each class.
3. Establish relationships among classes.3. Establish relationships among classes.
4. Create classes.4. Create classes.
Example 5.6 Borrowing Mortgages
Name firstname -mi -lastname +getFirstname +getMi +getLastname +setFirstname +setMi +setLastname +getFullname
1 1 Has Live
1 1
Mortgage
-annualInterestRate -numOfYears -loanAmount +getAnnualInterestRate +getNumOfYears +getLoanAmount +setAnnualInterestRate +setNumOfYears +setLoanAmount +monthlyPayment +totalPayment
Borrow
Borrower -name -address -mortgage +getName +getAddress +getMortgage +setName +setAddress +setMortgage
Address -street -city -state -zip +getStreet +getCity +getState +getZip +setStreet +setCity +setState +setZip +getAddress
NameNameBorrowerBorrower
AddressAddress
MortgageMortgage
Example 5.6 Borrowing Mortgages, cont.
The following is a test program that uses the The following is a test program that uses the classes classes NameName, , AddressAddress, , BorrowerBorrower, and , and MortgageMortgage. .
BorrowMortgageBorrowMortgage RunRun
Example 5.7Using the Rational Class
RationalRational
RunRun
1
1 Add, Subtract, Multiply, Divide
Rational
-numerator -denominator +Rational() +Rational(long numerator, int Denomination) +getNumerator +getDenominator +add(Rational secondRational) +multiply(Rational secondRational) +subtract(Rational secondRational) +divide(Rational secondRational) +toString() -gcd
Objective: Define a class for rational numbers that provides constructors and addition, subtraction, multiplication, and division methods.
TestRationalClassTestRationalClass
Java API and Core Java classes
java.langjava.lang
Contains core Java classes, such as Contains core Java classes, such as numeric classes, strings, and objects. This numeric classes, strings, and objects. This package is implicitly imported to every Java package is implicitly imported to every Java program.program.
java.awtjava.awt Contains classes for graphics.Contains classes for graphics.
java.appletjava.applet Contains classes for supporting applets.Contains classes for supporting applets.
java.iojava.io Contains classes for input and outputContains classes for input and outputstreams and files.streams and files.
java.utiljava.util Contains many utilities, such as date. Contains many utilities, such as date.
java.netjava.net Contains classes for supportingContains classes for supportingnetwork communications.network communications.
Java API and Core Java classes, cont.
java.awt.imagejava.awt.image
Contains classes for managing bitmap Contains classes for managing bitmap images.images.
java.awt.peerjava.awt.peer
Platform-specific GUI implementation. Platform-specific GUI implementation.
Others:Others:
java.sqljava.sql
java.rmijava.rmi
Java API and Core Java classes, cont.
The String Class Declaring a String:Declaring a String:
String message = "Welcome to Java!"String message = "Welcome to Java!" String message = new String("Welcome to Java!“);String message = new String("Welcome to Java!“); String s = new String();String s = new String();
String ComparisonsString Comparisons String ConcatenationString Concatenation SubstringsSubstrings String LengthString Length Retrieving Individual CharactersRetrieving Individual Characters
in a Stringin a String
String Comparisons
equalsequals
String s1 = "Welcome";String s1 = "Welcome";String s2 = "welcome";String s2 = "welcome";
if (s1.equals(s2)) if (s1.equals(s2)) // if the contents of s1 and s2 are// if the contents of s1 and s2 are { ... } { ... } // the same// the same if (s1 == s2) if (s1 == s2) // if s1 and s2 refer to same object// if s1 and s2 refer to same object
{{ … … }}
Substrings
String String is an immutable class; its valuesis an immutable class; its valuescannot be changed individually.cannot be changed individually.
String s1 = "Welcome to Java";String s1 = "Welcome to Java";
String s2 = s1.substring(0,10) + "HTML";String s2 = s1.substring(0,10) + "HTML";
Finding String Length
Finding string length using the Finding string length using the length()length() method:method:
message = "Welcome";message = "Welcome";
message.length() message.length() (returns(returns 7 7))
Retrieving Individual Characters in a String
Do not use Do not use message[0]message[0]
Use Use message.charAt(index)message.charAt(index)
Index starts from Index starts from 00
Example 5.8Finding Palindromes
Objective: CObjective: Checking whether a string hecking whether a string is a palindrome: a string that reads is a palindrome: a string that reads the same forward and backward. the same forward and backward.
FindPalindromeFindPalindrome RunRun
The StringBuffer Class
The The StringBufferStringBuffer class is an alternative to the class is an alternative to the StringString class. In general, a string buffer can be class. In general, a string buffer can be used wherever a string is used.used wherever a string is used.
StringBufferStringBuffer is more flexible than is more flexible than StringString. You . You can add, insert, or append new contentscan add, insert, or append new contentsinto a string buffer. However, the value ofinto a string buffer. However, the value ofa string is fixed once the string is created. a string is fixed once the string is created.
StringBuffer Constructors public StringBuffer()public StringBuffer()
No characters, initial capacity 16 characters.No characters, initial capacity 16 characters.
public StringBuffer(int length)public StringBuffer(int length)No characters, initial capacity specified by the No characters, initial capacity specified by the lengthlength argument. argument.
public StringBuffer(String str)public StringBuffer(String str)Represents the same sequence of charactersRepresents the same sequence of charactersas the as the stringstring argument. Initial capacity 16 argument. Initial capacity 16plus the length of the plus the length of the string string argument.argument.
Appending New Contentsinto a String Buffer
StringBuffer strBuf = new StringBuffer();StringBuffer strBuf = new StringBuffer();strBuf.append("Welcome");strBuf.append("Welcome");strBuf.append(' ');strBuf.append(' ');strBuf.append("to");strBuf.append("to");strBuf.append(' ');strBuf.append(' ');strBuf.append("Java");strBuf.append("Java");
The StringTokenizer Class Constructors StringTokenizer(String s, String delim, StringTokenizer(String s, String delim,
boolean returnTokens) boolean returnTokens)
StringTokenizer(String s, String delim)StringTokenizer(String s, String delim)
StringTokenizer(String s)StringTokenizer(String s)
The StringTokenizer Class Methods
boolean hasMoreTokens()boolean hasMoreTokens()
String nextToken()String nextToken()
String nextToken(String delim)String nextToken(String delim)
Example 5.10Testing StringTokenizer Objective: Using a string tokenizer, retrieve Objective: Using a string tokenizer, retrieve
words from a string and display them on the words from a string and display them on the console.console.
TestStringTokenizerTestStringTokenizer RunRun