Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Objects and Classes
Copyright © 2014 by John Wiley & Sons. All rights reserved.
1
Chapter Goals
To
To
To
To
understand the concepts of classes and objects
be able to call methods
implement classes and test programs
understand the difference between objects and object references
Copyright © 2014 by John Wiley & Sons. All rights reserved.
2
Objects as Models
A program can be thought of as a model of reality, with
objects in the program representing physical objects.
What Is an Object?
• a (software) object is a software construct/module that bundles
together state (data) and behavior (functions) which, taken
together, represent an abstraction of a real-world (physical or
conceptual) object.
Properties of objects:
• State (information stored within the object)
• Behavior (operations that can be performed
on the object)
operations are capable of changing an object’s state.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
3
E.g. Student Information System
Object: student
• State:
• studentID
• name
• transcript
• Behavior:
• register for course
• Find advisor
• Order transcript
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Object: professor
• State:
• emplyeeid
• name
• department
• Behavior:
• Teach course
• Assign grades
4
Student Registration System
Physical
Object
Properties
Functionalities
STUDENT
name, Id, courseList, major, transcript
Enroll(course), drop(course), getTranscript()
COURSE
name, cNo, credits, prerequisiteCourseList, professor, studentList
addStudent(student), dropStudent(student), getPrerequisites(),
verifyPrerequisiteCompletion(student)
PROFESSOR
name, id, department, courseList
agreeToTeach(course), assignGrade(course, student, grade)
TRANSCRIPT
Student, <course,grade>list
addTranscriptEntry(course, grade), completedPrerequisites()
OOP:
Java:
Mapped to
software objects
Object State
Object behaviour
Instance variables
Instance methods
Copyright © 2014 by John Wiley & Sons. All rights reserved.
5
Example objects in memory
TranscriptObject1
Student: StudentObject1
<course,grade>list =
<(CS150,A)>
StudentObject1
Name: Jim
Id: 1
courseList: <cs150>
Major: CS
transcript: transcriptObject1
StudentObject2
Name: Sam
Id: 2
courseList: <>
Major: undefined
transcript:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
CourseObject1
Name: CS Intro 1
cNo: CS150
prerequisiteCourseList= <>
Professor: ProfessorObject1
studentList=<>
ProfessorObject1
Name: Rasanjalee
Id: 772
Department: CS
courseList = <CS150, CS160
CourseObject2
Name: CS Intro 2
cNo: CS160
prerequisiteCourseList= <CS150>
Professor: ProfessorObject1
studentList=<>
6
Dynamic object interaction1: Jim register
for CS160 through bannerWeb
BANNER
Jim logged In
Course:
cs160
Student: StudentObject1
<course,grade>list =
<(CS150,A)>
enroll
1
TranscriptObject1
StudentObject1
CourseObject1
Name: Jim
Id: 1
StudentObject1.enroll(courseObject2)
courseList: <cs150, cs160>
Major: CS
transcript: transcriptObject1
2
3
Name: CS Intro 1
cNo: CS150
prerequisiteCourseList= <>
Professor: ProfessorObject1
studentList=<>
ProfessorObject1
Name: Rasanjalee
Id: 772
Department: CS
courseList = <CS150, CS160
CourseObject2.addStudent() CourseObject2.verifyPrerequisiteCompletion(studentObject1)
StudentObject2
Name: Sam
Id: 2
courseList: <>
Major: undefined
transcript:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
CourseObject2
Name: CS Intro 2
cNo: CS160
prerequisiteCourseList= <CS150>
Professor: ProfessorObject1
studentList=<StudentObject1>
7
Dynamic object interaction1: Jim register
for CS160 through bannerWeb
BANNER
Jim logged In
Course:
TranscriptObject1
After Interactions
cs160
Student: StudentObject1
<course,grade>list =
<(CS150,A)>
enroll
StudentObject1
Name: Jim
Id: 1
courseList: <cs150, CS160>
Major: CS
transcript: transcriptObject1
StudentObject2
Name: Sam
Id: 2
courseList: <>
Major: undefined
transcript:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
CourseObject1
Name: CS Intro 1
cNo: CS150
prerequisiteCourseList= <>
Professor: ProfessorObject1
studentList=<>
ProfessorObject1
Name: Rasanjalee
Id: 772
Department: CS
courseList = <CS150, CS160
CourseObject2
Name: CS Intro 2
cNo: CS160
prerequisiteCourseList= <CS150>
Professor: ProfessorObject1
studentList=<studentObject1>
8
Dynamic object interaction2: Rasanjalee assign
Jim a grade for CS160 through bannerWeb
BANNER
Rasanjalee logged In
Course:
Student:
Grade:
TranscriptObject1
cs160
Jim
B
assignGrade
Student: StudentObject1
<course,grade>list =
<(CS150,A)>
4
StudentObject1
ProfessorObject1.assignGrade(studentObject1, CS160, A)
CourseObject1
Name: Jim
Id: 1
courseList: <cs150, CS160>
major: CS
StudentObject1.getTranscript()
transcript: transcriptObject1
2
Name: CS Intro 1
cNo: CS150
prerequisiteCourseList= <>
Professor: ProfessorObject1
studentList=<>
ProfessorObject1
Name: Rasanjalee
Id: 772
Department: CS
courseList = <CS150, CS160
3
TranscriptObject1.verifyPrerequisiteCompletion(StudentObject1)
CourseObject2
StudentObject2
Name: Sam
Id: 2
courseList: <>
Major: undefined
transcript:
1
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Name: CS Intro 2
cNo: CS160
prerequisiteCourseList= <CS150>
Professor: ProfessorObject1
studentList=<>
9
Dynamic object interaction2: Rasanjalee assign
Jim a grade for CS160 through bannerWeb
BANNER
Rasanjalee logged In
Course:
Student:
Grade:
TranscriptObject1
cs160
Jim
B
assignGrade
StudentObject1
Student: StudentObject1
<course,grade>list =
<(CS150,A)
(CS160, B)
>
Name: Jim
Id: 1
courseList: <cs150, CS160>
major: CS
transcript: transcriptObject1
StudentObject2
Name: Sam
Id: 2
courseList: <>
Major: undefined
transcript:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
CourseObject1
Name: CS Intro 1
cNo: CS150
prerequisiteCourseList= <>
Professor: ProfessorObject1
studentList=<>
ProfessorObject1
Name: Rasanjalee
Id: 772
Department: CS
courseList = <CS150, CS160
CourseObject2
Name: CS Intro 2
cNo: CS160
prerequisiteCourseList= <CS150>
Professor: ProfessorObject1
studentList=<>
10
Student Registration System
Copyright © 2014 by John Wiley & Sons. All rights reserved.
11
Flight Reservation System
Copyright © 2014 by John Wiley & Sons. All rights reserved.
12
E.g. Airline Reservation System
Object: Flight
• State:
• scheduledDate
Object: Airport
• State:
• code
• name
• Behavior:
• check if it has room
• Add reservation
• Cancel reservation
Copyright © 2014 by John Wiley & Sons. All rights reserved.
• Behavior:
• Set address
13
Banking System
Copyright © 2014 by John Wiley & Sons. All rights reserved.
14
Inventory Control System
Copyright © 2014 by John Wiley & Sons. All rights reserved.
15
Classes
A class describes a set of objects with the same
behavior.
Examples of classes:
• Student
• Account
• Hotel
Copyright © 2014 by John Wiley & Sons. All rights reserved.
16
Classes vs Objects
The terms ‘class’ and ‘object’ are definitely related to one
another, but different.
Class:
• Blue print of objects
• actual written piece of code which is used to define common
properties and behaviors of any given class.
• Student class (variables = name, major, method=setMajor)
Object:
• An actual instance of a class.
• Every object must belong to a class.
• E.g. A Student object s1 with name=sam, major=biology
A Student object s2 with name=kim, major=physics
Copyright © 2014 by John Wiley & Sons. All rights reserved.
17
Example
pulbic class Student
{
int studentNo;
int age;
Implemented in java as Instance Variables
State/Attributes
public void addCourse(..)
{
....
}
public void dropCourse(..)
{
....
}
Implemented in java as Instance methods
Behavior
Two student objects created from class
}
Class
Copyright © 2014 by John Wiley & Sons. All rights reserved.
StudentObject1
StudentObject2
studentNo:1111
studentNo:2222
age: 26
age: 23
18
Declaring a class
Student.java
Initialize objects
(COVERED LATER)
The order of declarations usually doesn’t matter.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
19
Instance Variables
public class Student
{
private int studentNo;
private int age;
private String name;
private Professor advisor;
private List<Course> courses;
Some instance variables will
store a single value.
Others may store entire objects
public void addCourse(Course c)
{
courses.add(c);
}
public int getAge()
{
return age;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
20
Instance Methods
public class Student
{
private int studentNo;
private int age;
private String name;
private Professor advisor;
private List<Course> courses;
public void addCourse(Course c)
instance methods may update/change
{
instance variable values
courses.add(c);
}
public int getAge()
{
return age;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
instance methods may simply lookup
instance variable values
21
Instance Methods
public class Student
{
private int studentNo;
private int age;
private String name;
private Professor advisor;
private List<Course> courses;
instance methods may require
arguments
public void addCourse(Course c)
{
courses.add(c);
}
instance methods may return value
public int getAge()
{
return age;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
22
Declaring instance variables
public class Student
{
private int studentNo;
private int age;
private String name;
private Professor advisor;
private List<Course> courses;
Access modifier = private
Data type
Variable name
public void addCourse(Course c)
{
courses.add(c);
}
public int getAge()
{
return age;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
23
Declaring instance methods
pulbic class Student
{
private int studentNo;
private int age;
private String name;
private Professor advisor;
private List<Course> courses;
Access modifier Return type Method name Optional list of comma separated parameters
(type name)
public void addCourse(Course c)
{
courses.add(c);
}
public int getAge()
{
return age;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
}
24
Access Modifiers
pulbic class Student
{
• Instance variables are usually private.
private int studentNo;
• i.e. Variable accessible only within class
private int age;
• Called INFORMATION HIDING
private String name;
private Professor advisor;
private List<Course> courses;
Access modifier = private
public void addCourse(Course c)
{
courses.add(c);
}
public int getAge()
{
return age;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
constructors and instance methods are
usually public.
25
Creating Objects from Classes
We did not write any constructors
You will learn how to write constructors later.
If no constructors are written, Java provides a default
constructor that does nothing
You can create objects of such a class as follows:
E.g. public class StudentDemo {
public static void main(String args[]) {
Student s1 = new Student();
Class
Name
Object
Name
new
Class
keyword Name
Open close parenthsis
No arguments
Student s2 = new Student();
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
26
Calling a method on a object
Syntax: Dot notation
• objectName.methodName(optional parameters)
public class StudentDemo {
public static void main(String args[]) {
Student s1 = new Student();
int age = s1.getAge();
Return type var
Name
Name
Object
Name
Method
Name
Student s2 = new Student();
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
27
Programming Question
BankAccount.java
• Write a class BankAccount.java that represents a bankaccount
• Instance variables:
• balance (double)
• Instance methods:
•
•
•
•
deposit : parameters(amount), return : none
withdraw: parametrs(amount), return: none
getBalance: parameters(none), return : current balance
close: parameters(none), return : none
Create a BankAccountDemo class to
•
•
•
•
•
Create a bankaccount object
Deposit $100 to account object
Print before and after balance
Withdraw $10 from account object
Print before and after balance
Copyright © 2014 by John Wiley & Sons. All rights reserved.
28
Answer
BankAccount.java
BankAccountDemo.java
Copyright © 2014 by John Wiley & Sons. All rights reserved.
29
Accessor and Mutator Methods
Accessor method:
• does not change the internal data of the object on
which it is invoked.
• E.g. getBalance method of BankAccount class
Mutator method:
• changes the data of the object
• E.g. withdraw and deposit methods of BankAccount
class
Copyright © 2014 by John Wiley & Sons. All rights reserved.
30
Private access modifier
Copyright © 2014 by John Wiley & Sons. All rights reserved.
31
Programming Question
Implement a tester class BankAccountTester to test
the functionality of BankAccount class. In the main
method do following:
1. create two BankAccount objects, harrysChecking and
momsSavings. harrysChecking should have $5000 at
creation and momsSavings, $0.
2. Withdraw $500 from harrysChecking
3. Deposit $2000 to momsSavings
4. Print current balance of both accounts
Sample output:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
32
Answer
BankAccountTester.java
public class BankAccountTester
{
public static void main(String args[])
{
BankAccount harrysChecking = new BankAccount(5000.0);
BankAccount momsSavings = new BankAccount();
harrysChecking.withdraw(500.0);
momsSavings.deposit(2000);
double harrysBalance = harrysChecking.getBalance();
double momssBalance = momsSavings.getBalance();
System.out.println(" harrysChecking balance = "+ harrysBalance);
System.out.println(" momsSavings balance = "+ momssBalance);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
33
Answer
Improved version
public class BankAccountTester
{
public static void main(String args[])
{
BankAccount harrysChecking = new BankAccount(5000.0);
BankAccount momsSavings = new BankAccount();
harrysChecking.withdraw(500.0);
momsSavings.deposit(2000);
System.out.println(" harrysChecking balance = "+ harrsChecking.getBalance());
System.out.println(" momsSavings balance = "+ momsSavings.getBalance());
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
34
Method Overloading
Methods can be overloaded.
i.e. A class can contains more than one method with the
same name.
The overloaded methods must have :
• different numbers of parameters or
• some difference in the types of the parameters.
Overloading is best used for methods that perform
essentially the same operation.
The advantage of overloading: Fewer method names to
remember.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
35
Example
Copyright © 2014 by John Wiley & Sons. All rights reserved.
36
Example of 3 overloaded methods add:
public class Calculator
{
public int add(int a, int b)
{
return a+b;
}
public double add(double a, double b)
{
return a+b;
}
public int add(int a, int b, int c)
{
return a+b+c;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
37
Example
Copyright © 2014 by John Wiley & Sons. All rights reserved.
38
Declaring Constructors
When an object is created, its instance variables are initialized by a
constructor.
A constructor looks like an instance method
But has no return type
name is the same as the name of the class itself.
A constructor for the BankAccount class:
public BankAccount(double initialBalance) {
balance = initialBalance;
}
A class may have more than one constructor (overloaded
constructors possible).
default constructor
• No argument empty-body constructor provided by java
• lost as soon as you define your own constructors
Copyright © 2014 by John Wiley & Sons. All rights reserved.
39
Example
Copyright © 2014 by John Wiley & Sons. All rights reserved.
40
Copyright © 2014 by John Wiley & Sons. All rights reserved.
41
Programming Question
Implement a class BankAccount.java that contains
following:
• Attributes/instance variables:
• balance
• 2 overloaded Constructors
• no-argument constructor : sets balance to zero
• One argument constructor: takes one parameter-initial balance. Set balance to
initial balance
Copyright © 2014 by John Wiley & Sons. All rights reserved.
42
Answer
BankAccount.java
public class BankAccount{
private double balance;
//constructor: initialze balance to zero
public BankAccount() {
balance = 0.0;
}
//constructor: intialize balance to initial balance
public BankAccount(double initialBalance) {
balance = initialBalance;
}
public void deposit(double amount)
balance += amount;
}
public void withdraw(double amount)
balance -= amount;
}
public double getBalance()
return balance;
}
{
{
{
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
43
Question
Change access modifier of deposit method to private.
How does this change output of
BankAccountDemo.java?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
44
Answer
Calling deposit method on account object results in a
compiler error.
This is because deposit method is privateand not
accessible outside BankAccount class anymore.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
45
How primitive values are Stored
A variable of a primitive (non-object) type can be
visualized as a box:
int i;
Assigning a value to the variable changes the value
stored in the box:
i = 0;
Copyright © 2014 by John Wiley & Sons. All rights reserved.
46
Creating Objects
Once a class has been declared, it can be used to
create objects (instances of the class).
Each object/instance will contain its own copy of the
instance variables declared in the class.
A newly created object can be stored in a variable
whose type matches the object’s class:
BankAccount acct;
Technically, acct will store a reference to an Account
object, NOT the object itself.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
47
account has value null.
i.e. it is not pointing to a
BankAccount object yet
account points to newly
created object. Memory
Address where object is stored printed.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
48
How state of memory changes when you
create objects
BankAccount harrysChecking;
Memory
harrysChecking
Copyright © 2014 by John Wiley & Sons. All rights reserved.
49
How state of memory changes when you
create objects
BankAccount harrysChecking;
Memory
harrysChecking = new BankAccount();
harrysChecking
balance=0.0
Copyright © 2014 by John Wiley & Sons. All rights reserved.
50
How state of memory changes when you
create objects
BankAccount harrysChecking;
Memory
harrysChecking = new BankAccount();
BankAccount momsSavings;
harrysChecking
balance=0.0
momsSavings
Copyright © 2014 by John Wiley & Sons. All rights reserved.
51
How state of memory changes when you
create objects
BankAccount harrysChecking;
Memory
harrysChecking = new BankAccount();
BankAccount momsSavings;
harrysChecking
balance=0.0
momsSavings = new BankAccount(100.0);
momsSavings
balance=100.0
Copyright © 2014 by John Wiley & Sons. All rights reserved.
52
The null Keyword
To indicate that an object variable doesn’t currently point
to an object, the variable can be assigned the value null:
acct = null;
When an object variable stores null, it’s illegal to use the
variable to call an instance method.
If acct has the value null, executing the following
statement will cause a run-time error
(NullPointerException):
acct.deposit(500.00);
Copyright © 2014 by John Wiley & Sons. All rights reserved.
53
Example2
No errors when acct
references a
BankAccount object
Error occurs when acct
DOES NOT references
a BankAccount object
Copyright © 2014 by John Wiley & Sons. All rights reserved.
54
Question
Q. Object construction
For each class below, look the class up in the java documentation and come up with a
way to construct an object for that class.
a.
b.
c.
d.
e.
f.
Random // a class for generating random numbers
Scanner // a class for reading tokens from an input stream
String // a class representing sequences of chars
Point // a class representing 2D points
System // a class representing the operating system
Math // a class representing mathematics
Copyright © 2014 by John Wiley & Sons. All rights reserved.
55
Question
Q. Object construction
For each class below, look the class up in the java documentation and come up with a way to construct an object for that class.
a.
Random // a class for generating random numbers
ANSWER:Random rand = new Random();
a.
Scanner // a class for reading tokens from an input stream
ANSWER:
Scanner input = new Scanner(System.in); or
Scanner input = new Scanner(); or
Scanner input = new Scanner(“input string”);
Scanner input = new Scanner(new File(“bar.txt”));
a.
String // a class representing sequences of chars
ANSWER:
String s = “”;
String s = new String(“foo”);
String s = new String(new char[20]);
a.
Point // a class representing 2D points
ANSWER:
Point p = new Point();
Point p = new Point(1, 7);
a.
System // a class representing the operating system
ANSWER:
The System class has no (public) constructor
you cannot create an object for this class.
a.
Math // a class representing mathematics
ANSWER:
The Math class has no public) constructor
you cannot create an object for this class
Copyright © 2014 by John Wiley & Sons. All rights reserved.
56
Primitive variable Assignment
If i has the value 10, assigning i to j gives j the
value 10 as well:
j = i;
Changing the value of i has no effect on j:
i = 20;
Assignment of objects doesn’t work the same way.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
57
Object Assignment
Assigning acct1 to acct2 causes acct2 to refer to
the same object as acct1:
BankAccount object
acct2 = acct1;
acct1 and acct2 represent the same object.
Then the statement
acct1.deposit(500.00);
will change the balance of acct2 to $1000.00:
BankAccount object
Now both acct1.getBalance() and
acct2.getBalance() will return 1000.0
Copyright © 2014 by John Wiley & Sons. All rights reserved.
58
Example
Same memory address:
i.e. both variables refer same
BankAccount object in the memory
Copyright © 2014 by John Wiley & Sons. All rights reserved.
59
Programming Question
1. Implement a class Rectangle that models a rectangle. Class has :
• 4 instance variables: x(start x), y (start y), width, and height
• 2 methods: getX () that reurn x value and translate(int dx, int dy)
that moves rectangle by dx pixels in x direction and by dy pixels in y
direction
• One 4-arg constructor: initialize all four instance variables to values
provided as parameters.
2. Write a RectangleTester class that create a rectangle, translate it by
dx=5, dy =10 and print x value before and after translate is called.
Sample output:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
60
Answer
Rectangle.java
public class Rectangle
{
int x;
int y;
int width;
int height;
public Rectangle(int xval, int yval, int w, int h)
{
x = xval;
y=yval;
width = w;
height = h;
}
public int getX()
{
return x;
}
public void translate(int dx, int dy)
{
x += dx;
y += dy;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
61
RectangleTester.java
public class RectangleTester
{
public static void main(String args[])
{
Rectangle rectangle = new Rectangle(5,10,20,25);
System.out.println("x before: "+rectangle.getX());
rectangle.translate(25,25);
System.out.println("x after: "+rectangle.getX());
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
62
The this Reference
this is a reference variable denoting current object.
You can refer to any member of the current object
from within an instance method or a constructor by
using this.
E.g.
balance = balance + amount;
actually means
this.balance = this.balance + amount;
When you refer to an instance variable in a method,
the compiler automatically applies it to the this
reference.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
63
The this Reference
Using this reference is not required.
Some programmers feel that inserting the this
reference before every instance variable reference
makes the code clearer:
public BankAccount(double initialBalance)
{
this.balance = initialBalance;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
64
State of memory
1
harrysChecking
balance=0.0
this
harrysChecking
balance=0.0
momsSavings
balance=5000.0
2
this
3
4
harrysChecking
balance=0.0
this
momsSavings
balance=5000.0
harrysChecking
balance=0.0
momsSavings
balance=6000.0
this
Copyright © 2014 by John Wiley & Sons. All rights reserved.
amount
1000.0
65
Usage of this keyword
this keyword can be used to:
1.
2.
3.
4.
5.
6.
refer current class instance variable
invoke current class constructor.
invoke current class method
return the current class instance.
pass as argument in the constructor call.
pass as an argument in the method call.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
66
Using this with a Field
1. Refer current class instance variable
Parameter variable x
Rectangle class
with this keyword
Instance variable x
Copyright © 2014 by John Wiley & Sons. All rights reserved.
67
The this Reference
The this reference can be used to distinguish between
instance variables and local or parameter variables:
A local variable shadows an instance variable with the same
name.
• You can access the instance variable name through the this
reference.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
68
Programming Question
Using this with a Field:
Modify BankAccount class to use this keyword to
refer to current instance variables
Copyright © 2014 by John Wiley & Sons. All rights reserved.
69
Answer
Copyright © 2014 by John Wiley & Sons. All rights reserved.
BankAccount.java
70
Using this with a Constructor
2. invoke current class constructor.
From within a
constructor,
you can this
keyword to call
another
constructor in
the same class.
If present, the
invocation of
another
constructor
must be the
first line in the
constructor.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
71
Programming Question
Using this with a constructor:
Modify BankAccount class no argument constructor so
that it calls the one argument constructor to set the
initial balance to 0.0.
public BankAccount()
public BankAccount(double balance)
Copyright © 2014 by John Wiley & Sons. All rights reserved.
72
Answer
Copyright © 2014 by John Wiley & Sons. All rights reserved.
BankAccount.java
73
Using this Reference for Method Calls
3. Invoke current class method
You may invoke the method of the current class by
using the this keyword.
If you don't use the this keyword, compiler
automatically adds this keyword while invoking the
method.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
74
The this Reference for Method Calls
E.g.
Method call using
this reference
Copyright © 2014 by John Wiley & Sons. All rights reserved.
75
Garbage
Objects can become “orphaned” during program
execution.
Consider the following example:
BankAccount acct1= new BankAccount(100.0);
BankAccount acct2= new BankAccount(200.0);
acct1 = acct2;
After these assignments, the object that acct1
previously referred to is lost.
We say that it is garbage.
Ref: Java Programming: From the Beginning - KN King
Copyright © 2014 by John Wiley & Sons. All rights reserved.
76
76
Acct1 references the same
object that acct2 references
Original object acct1 referenced
now has no references pointing to it.
So now it becomes a garbage object
Copyright © 2014 by John Wiley & Sons. All rights reserved.
77
BankAccount object
Garbage
Object
(i.e. no references to it)
BankAccount object
Copyright © 2014 by John Wiley & Sons. All rights reserved.
78
Garbage Collection
Java provides automatic garbage collection: as a Java
program runs, a software component known as the
garbage collector watches for garbage and periodically
“collects” it.
The recycled memory can be used for the creation of
new objects.
Garbage collection normally takes place when the
program isn’t doing any other useful activity.
Ref: Java Programming: From the Beginning - KN King
Copyright © 2014 by John Wiley & Sons. All rights reserved.
79
79
Strings and Characters
Characters:
• A character is a value of the type char.
• Characters have numeric values
• Character literals are delimited by single quotes.
• E.g. char ch = ‘a’;
• Don't confuse them with strings
• "H" is a string containing a single character.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
80
Unicode Characters
Copyright © 2014 by John Wiley & Sons. All rights reserved.
FROM: http://www.utf8-chartable.de/unicode-utf8-table.pl?utf8=dec
81
String:
• A string is a sequences of Unicode characters.
• String is a class in java library
• String is the only class whose instances can be created without
the word new:
String str1 = "abc";
This is an example of magic. [IS IT ANYMORE?]
Copyright © 2014 by John Wiley & Sons. All rights reserved.
82
Common String Methods: charAt
Each character in a string is identified by a position
Positions start with 0.
The String class has a large number of instance methods.
The charAt method returns a char value from a string
E.g.
String name = "Harry”;
char start = name.charAt(0); //set start value to ‘H’
char last = name.charAt(4); //set last value t ‘y’
Copyright © 2014 by John Wiley & Sons. All rights reserved.
83
Copyright © 2014 by John Wiley & Sons. All rights reserved.
84
Example
Copyright © 2014 by John Wiley & Sons. All rights reserved.
85
Common String Methods: indexOf
One version of the indexOf method searches for a string
(the “search key”) within a larger string, starting at the
beginning of the larger string.
Example: Locating the string "at" within str1:
• Assume str1 = “Fat Cat”;
index = str1.indexOf("at");
After this assignment, index will have the value 1.
If "at" had not been found anywhere in str1, indexOf
would have returned –1.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
86
Example
Copyright © 2014 by John Wiley & Sons. All rights reserved.
87
Common String Methods: length
The length method returns the number of characters
in a string.
E.g
String name = "Harry”;
int length = name.length(); //returns 5
Copyright © 2014 by John Wiley & Sons. All rights reserved.
88
88
Common String Methods
toLowerCase and toUpperCase will convert the letters in a
string to lowercase or uppercase.
Assume str1 = “Fat Cat”;
After the assignment
String str2 = str1.toLowerCase();
the value of str2 is "fat cat".
After the assignment
String str2 = str1.toUpperCase();
the value of str2 is "FAT CAT".
Characters other than letters aren’t changed by
toLowerCase and toUpperCase.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
89
Only letters change
Original string s remains unchanged
Copyright © 2014 by John Wiley & Sons. All rights reserved.
90
Common String Methods: trim
The trim method removes spaces (and other invisible
characters) from both ends of a string.
After the assignments
String str1 = " How now,
String str2 = str1.trim();
the value of str2 will be
"How now, brown
Copyright © 2014 by John Wiley & Sons. All rights reserved.
brown
cow?
";
cow?"
91
Copyright © 2014 by John Wiley & Sons. All rights reserved.
92
Common String Methods: Substrings
Use the substring method to extract a part of a string.
The method call str.substring(start, pastEnd)
• returns a string that is made up of the characters in the string str,
• starting at position start, and
• containing all characters up to, but not including, the position pastEnd.
Example:
String greeting = "Hello, World!”;
String sub = greeting.substring(0, 5); // sub is "Hello”
Retrieve substring in index range 0-4;
Index=5 is excluded
Copyright © 2014 by John Wiley & Sons. All rights reserved.
93
Chaining Calls of Instance Methods
When an instance method returns an object, that
object can be used to call another instance method.
For example, the statements
str2 = str1.trim();
str2 = str2.toLowerCase();
can be combined into a single statement:
str2 = str1.trim().toLowerCase();
Copyright © 2014 by John Wiley & Sons. All rights reserved.
94
94
Programming Question
Write a tester class StringTester that test the use of
String class. The program should first prompt the user
for first name and store it in a appropriate variable.
Then it should prompt the user again to enter his/her
significant other’s first name and store it in a
appropriate variable. Finally program will display the
First Initials combined by & sign.
Following is sample run:
Enter your first name: Rodolfo
Enter your significant other's first name: Sally
R&S
Copyright © 2014 by John Wiley & Sons. All rights reserved.
95
Answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
23
24
25
StringTester.java
import java.util.Scanner;
/**
This program prints a pair of initials.
*/
public class StringTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
// Get the names of the couple
System.out.print("Enter your first name: ");
String first = in.next();
System.out.print("Enter your significant other’s first name: ");
String second = in.next();
// Compute and display the inscription
String initials = first.substring(0, 1) + "&" + second.substring(0, 1);
System.out.println(initials);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
96
Copyright © 2014 by John Wiley & Sons. All rights reserved.
97
Programming Question
Modify StringTester class so that it include an input
statement to read a name of the form “John Q. Public”.
Sample run is shown below:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
98
Answer
Answer:
String first = in.next();
String middle = in.next();
String last = in.next();
Copyright © 2014 by John Wiley & Sons. All rights reserved.
99
Testing Objects for Equality
If x and y are two object variables of the same type,
the expression
x == y
tests whether x and y refer to the same object (or both
x and y have the value null).
The references in x and y are being compared, NOT
the objects that x and y refer to.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
100
Even if two
different object
have same
content,
statement return
false
Both null :
statement return true
Copyright © 2014 by John Wiley & Sons. All rights reserved.
if two reference
variables
reference same
object ,statement
return true
101
The equals Method
The equals method is used to test whether two
objects contain matching data.
The value of x.equals(y) is true if the objects that x
and y represent are “equal.”
Every Java class supports the equals method,
although the definition of “equals” varies from class to
class.
For some classes, the value of x.equals(y) is the
same as x == y.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
102
Copyright © 2014 by John Wiley & Sons. All rights reserved.
103
Comparing Strings
When comparing strings, same rule that apply to other
objects apply to strings
To test whether two strings are equal to each other, use
equals method:
if (string1.equals(string2)) . . .
Don't use == for strings!
if (string1 == string2) // Not useful
== operator:
• tests if two strings are stored in the same memory location
equals method:
•
tests equal contents
Copyright © 2014 by John Wiley & Sons. All rights reserved.
104
Programming Question
Write a class ObjectComparisonTester.java Include following code in your
main method to initialize Rectangle objects(java.awt.Rectangle):
Rectangle box1 = new Rectangle(5, 10, 20, 30);
Rectangle box2 = box1;
Rectangle box3 = new Rectangle(5, 10, 20, 30);
Also include statements to test and print if each possible pair of Rectangle
reference variables:
1.
2.
refer to the same Rectangle object in memory and
Refer to Rectangle objects that contain the same content
Sample run is shown:
Copy and modify template from:
/net/people/classes/CS160/handouts/cs160_source_code/lec3/templates/ObjectComparisonTester.java
Copyright © 2014 by John Wiley & Sons. All rights reserved.
105
Answer
ObjectComparisonTester.java
import java.awt.Rectangle;
public class ObjectComparisonTester
{
public static void main(String args[])
{
Rectangle box1 = new Rectangle(5,10,20,30);
Rectangle box2 = box1;
Rectangle box3 = new Rectangle();
//test and print if box1 and box2 reference same object
System.out.println("box1==box2:"+(box1==box2));
//test and print if box1 and box3 reference same object
System.out.println("box1==box3:"+(box1==box3));
//test and print if box2 and box3 reference same object
System.out.println("box2==box3:"+(box2==box3));
//test and print if box1 and box2 contain same data
System.out.println("box1.equlas(box2):"+(box1.equals(box2)));
//test and print if box1 and box3 contain same data
System.out.println("box1.equlas(box3):"+(box1.equals(box3)));
//test and print if box2 and box3 contain same data
System.out.println("box2.equlas(box3):"+(box2.equals(box3)));
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
106
Object Comparison
Rectangle box1 = new Rectangle(5, 10, 20, 30);
Rectangle box2 = box1;
Rectangle box3 = new Rectangle(5, 10, 20, 30);
Copyright © 2014 by John Wiley & Sons. All rights reserved.
107
Testing for null
null reference refers to no object:
String middleInitial = null; // Not set
Can be used in tests:
if (middleInitial == null)
{
System.out.println(firstName + " " + lastName);
}
else
{
System.out.println(firstName + " " +
middleInitial + ". " + lastName);
}
Use ==, (not the equals method), to test for null
null is not the same as the empty string ""
Copyright © 2014 by John Wiley & Sons. All rights reserved.
108
Wrapper classes
Found in java.lang package
“Wrap" primitive values in an object
Primitive Type
byte
int
double
float
long
short
char
boolean
Wrapper Class
Byte
Integer
Double
Float
Long
Short
Character
Boolean
Provide an assortment of utility functions
• E.g. converting primitives to and from String objects,
Copyright © 2014 by John Wiley & Sons. All rights reserved.
109
Integer class
Copyright © 2014 by John Wiley & Sons. All rights reserved.
110
Specifying the Public Interface of a Class
public constructors and methods of a class form the
public interface of the class.
These are the operations that any programmer can use.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
111
Commenting the Public Interface – Documenting a Class
Provide documentation comments for:
•
•
•
•
every
every
every
every
class
method
parameter variable
return value
Copyright © 2014 by John Wiley & Sons. All rights reserved.
112
Commenting the Public Interface –Documenting a Method
Start the comment with a /**. End with */.
Here are some common pre-defined tags:
@author [author name]
•
identifies author(s) of a class or interface.
@version [version]
• version info of a class or interface.
@param [argument name] [argument description]
• describes an argument of method or constructor.
@return [description of return]
• describes data returned by method (unnecessary for constructors and
void methods).
@exception [exception thrown] [exception
description]
• describes exception thrown by method.
@throws [exception thrown] [exception description]
• same as @exception.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
113
Example: Documented Employee class
/**
* This class models an Employee.
* @author Rasanjalee Dissanayaka
*/
public class Employee{
private int age;
private String name;
/**
* constructor, initialize employee with given name
* @param empName the name of the employee
* @param empAge the age of the employee
*/
public Employee(String empName, int empAge){
name = empName;
age = empAge;
}
/**
* set the age of the employee
* @param empAge the age of the employee
*/
public void setAge(int empAge){
age = empAge;
}
/**
* returns the age of the employee
* @return the age of the student
*/
public int getAge(){
return age;
}
Copyright
© 2014 by John Wiley & Sons. All rights reserved.
}
114
Commenting the Public Interface –
Documenting a Class
Javadoc Compilation
• To generate the html documentation, run Javadoc followed by the
list of source files, which the documentation is to be generated
for, in the command prompt /terminal window
• E.g.
c:\MyWork> javadoc A.java B.java c:\OtherWork\*.java
• Using DrJava:
• ToolsJavdocJavadoc All documentsselect locationclick ok
Copyright © 2014 by John Wiley & Sons. All rights reserved.
115
Copyright © 2014 by John Wiley & Sons. All rights reserved.
116
Programming Question
Modify BankAccount class to include javadoc
comments at class, method, parameter and return
value levels.
Generate javadoc documentation for the file.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
117
Answer
Copyright © 2014 by John Wiley & Sons. All rights reserved.
BankAccount.java
118
Copyright © 2014 by John Wiley & Sons. All rights reserved.
119
Question
Change access modifier of deposit method to private.
How does this change the generated javadoc
API?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
120
Answer
That means deposit method is not part of the public
interface of BankAccount class anymore.
So, it is not shown in javadoc API page
Copyright © 2014 by John Wiley & Sons. All rights reserved.
121
References
Java Programming from the beginning, KN King
Copyright © 2014 by John Wiley & Sons. All rights reserved.
122