Vous êtes sur la page 1sur 54

CSCI 1302

Programming Principles II
Spring 2014
Instructor: Wenjia Li
01/07/16

Contact Information
Who am I?
Wenjia Li

Best way to contact me?


Email! wenjiali@georgiasouthern.edu
Please put CSCI 1302 in your subject
line

Office hours:
Where?
CIT 2307

When?
Tu & Th 130 PM to 2 PM and Wed 2 PM to 4 PM
AND by appointment
01/07/16

Am I in the RIGHT Class?


CSCI 1302 (Programming Principles II)
Goal: make you
Understand object-oriented programming with
GUI
Learn how to develop more advanced Java
programs (when compared to CSCI
1236/1301)

What will be covered:


Classes/objects, composition, inheritance,
polymorphism, GUI, exception, generics, etc.
Full list of topics shown in Syllabus
01/07/16

Object-oriented
Language
Procedural languages (such as C, Pascal,
BASIC, Ada, and COBOL) are composed of
procedures (or functions, or methods). Each
procedure deals with a dedicated task.
Data and operations on data are separate.

An object-oriented language (such as


Java) combines the power of procedural
languages with the usage of classes and
objects.
Data and operations on data are unified within a
single entity called object.
4

Why Classes and


Objects?

Assemble car in 1909

Assemble car
NOWADAYS

What is An Object?
An object represents a distinct entity in
the real world
E.g., a car, a student, a bank account

An object has a unique identity, state


and behaviors.
The state of an object consists of set of
fields with current values (E.g, variables in
Java)
A behavior of an object is a way to
manipulate the data (E.g., methods in Java)
6

Example of Objects
Data field 1

Capital
State

Data field n

State

Term

Method 1

Interest_Rate

Compute_Balance
Behavio
r

Behavio
r

Method m
An
Object

A bank
account
7

How about Class?


A class is a programming construct that
defines objects of the same type.
A class is blueprint or scheme that defines
what an objects data and method will be like.

Creating an instance of a class is referred


to as instantiation.
An object is an instance of a class.

The relation between a class and an object


of the class is similar to the relation
between a primitive data type and a
variable of the type.
8

Creating Objects
Remember that a class is like a data type:
one can create variables of the class (namely
objects of the class) using the same way as
they declare variables of other data types:
Declaration:
class_name object_name;

Creation
object_name = new class_name( );

Or you may combine them together:


class_name

object_name = new class_name( );

Object Assignment
Like arrays, the assignment of objects is
essentially making references.
For primitive data variables, the assignment is copying
values (instead of making references).
In following example, the old a1 becomes garbage
after assignment; Java reclaims its memory
automatically.

Account a1,a2;
a1 = a2;

a1

a2
Before
assignme

Capital =100;
Rate=0.02

Capital =2000;
Rate=0.04

a1

a2
After
assignme
10
nt

Accessing Class
Members
Recall the way we accessed library
methods and data:
JOptionPane.showInputDialog( );
Math.random( );
Math.PI;

The general rule is


Object_Name.Member_name;
Class_name.Member_name; // If the member
being accessed is static.
Example: getMileage V.S. getAllModel
11

An Example

public class TestAccount {


public static void main(String[] args) {
Account Josh = new Account( );
Account Bob = new Account( );
Josh.Capital = 200.50; Josh.Rate=0.02; Josh.Term=5;
Bob.Capital=1000.07; Bob.Rate=0.04; Bob.Term=10;
System.out.println(Josh account balance will be +Josh.Compute_Balance( ));
System.out.println(Bob account balance will be +Bob.Compute_Balance( ));
System.exit(0);
}
} //End of class TestAccount
class Account {
double Capital, Rate;
int Term;
double Compute_Balance( ){
return Math.pow(1+Rate, Term)*Capital;
}
} // End of class Account
12

Constructors
We would like to create accounts somehow
more automatically.
automatically
Can we create an account by also specifying
Capital, Rate, and Term when we declare an
object?

The solution is to use constructors.


A constructor is a special member method of the
class.
The name of a constructor is the same as the
class name (special, huh?).
A constructor has NO return type, NOT EVEN the
void (even MORE special, huh?).
13

Constructors (Cont.)
We can have more than one constructors
in a class.
Constructors are thus overloaded methods.

A constructor is automatically called when


an object is created in accordance to its
signature.
This is like the way automatically pick an
overloaded methods by examining the
matches of the types of actual parameters with
the signature of the method.
14

public class TestAccount2 {


public static void main(String[] args) {
Account Josh = new Account(200.50, 0.02, 5 );
Account Bob = new Account(100.07);
Bob.Rate=0.04; Bob.Term=10;
System.out.println(Josh account balance will be +Josh.Compute_Balance( ));
System.out.println(Bob account balance will be +Bob.Compute_Balance( ));
System.exit(0);
}
}//End of class TestAccount2
class Account {
double Capital, Rate;
int Term;
double Compute_Balance( ) {
return Math.pow(1+Rate, Term)*Capital;
}
Account(double c, double r, int t) { // One constructor
Capital = c; Rate = r; Term = t;
}
Account(double c) { // Another constructor
Capital = c;
}
} // End of class Account
15

Default Constructor
Observation: A class may be
declared without constructors.
In this case, a no-arg constructor
with an empty body is implicitly
declared in the class.
Called default constructor
It is provided automatically only if no
constructors are explicitly declared in
the class.
01/07/16

16

Array of Objects
Like creating/using an array of primitive
data variables, one can create an array
of objects (class variables).
Declaration & memory allocation
Account[] array = new Account[900];

Initialization (use for loop)


for(int j=0; j<900; j++)
Array[j]=new Account( ); // You may choose another
constructor

17

Visibility Modifiers for


Members
The examples we have seen have a potential
problem: An object can modify the data fields
directly.
How about a patient access/modify the medical
record of another patient?

Java provides private and public modifiers to


control the access level.
Public defines classes, methods, and data in such
a way that all programs can access them.
Private defines methods and data in such a way
that they can be accessed by its parent class, but
not any other class.
Default: public
18

How to Access Private


Data?
Since private can only be accessed by the
member methods in the same defining
class. The following should be a right
solution to access private data:
Create a public member method that accesses
data in the desired way.
Call the method (since it is public!) using objects.

This kind of members is called mutators or


accessor methods.
Set/Get methods

Typically, constructors should be public.


19

public class TestAccount3 {


public static void main(String[] args) {
Account Bob = new Account(100.07);
// Wrong!: Bob.Rate=0.04; Bob.Term=10; Use the following
Bob.set_rate_term(0.04, 10);
System.out.println(Bob account balance will be +Bob.Compute_Balance( ));
System.exit(0);
}
}
class Account {
private double Capital, Rate;
private int Term;
public double Compute_Balance( ) {
return Math.pow(1+Rate, Term)*Capital;
}
public Account(double c) { // constructor
Capital = c;
}
public void set_rate_term(double r, int t) { // A mutator
Rate = r; Term =t ;
}
} // End of class Account
20

Passing Objects to
Methods
Like passing array, passing objects to
a method is passing by reference.
What is needed to pass is the name
of the object. (just like passing arrays
and variables of primitive data
types).

21

Immutable Objects and


Classes
Definition: If the contents of an object
cannot be changed once the object is
created, the object is called an immutable
object and its class is called an immutable
class.
What Class is Immutable?
For a class to be immutable, it must mark all
data fields private and provide no mutator
methods and no accessor methods that would
return a reference to a mutable data field object.
01/07/16

22

The this Keyword


The this keyword is the name of a
reference that refers to an object
itself.
Two common usages
Refer to a classs hidden data fields.
Enable a constructor to invoke another
constructor of the same class.
01/07/16

23

Reference to the Hidden


Data Fields
public class Foo {
private int i = 5;
private static double k = 0;
void setI(int i) {
this.i = i;
}

Suppose that f1 and f2 are two objects of Foo.


Invoking f1.setI(10) is to execute
this.i = 10, where this refers f1
Invoking f2.setI(45) is to execute
this.i = 45, where this refers f2

static void setK(double k) {


Foo.k = k;
}
}

01/07/16

24

Calling Overloaded
Constructor

public class Circle {


private double radius;

public Circle(double radius) {


this.radius = radius;
}
this must be explicitly used to reference the data
field radius of the object being constructed

public Circle() {
this(1.0);
}

this is used to invoke another constructor

public double getArea() {


return this.radius * this.radius * Math.PI;
}
Every instance variable belongs to an instance represented by this,
which is normally omitted
01/07/16

25

Class Abstraction and


Encapsulation
Class abstraction means to separate
class implementation from the use of
the class.
The creator of the class provides a
description of the class and let the user
know how the class can be used.
The user of the class does NOT need to
know how the class is implemented.

The detail of implementation is


encapsulated and hidden from the user.
01/07/16

26

Composition

01/07/16

27

Code Reuse
Effective software development relies on
reusing existing code.
Code reuse must be more than just
copying code and changing it which is
often the case with procedural languages
like C.
Goal with OOP languages: reuse
classes without changing the code within
the class
one OOP technique for code reuse is known
as composition.
01/07/16

28

A Simple Database
Your favorite boss wishes to implement a simple database of
Motorcycles they currently have on the dealerships lot.
Their application has only a few requirements...
They would like record the VIN, Color, Date of Arrival, and
Date of Sale each Motorcycle that has entered and left the
dealership. A report is required that prints all information for
each Motorcycle. Motorcycles must be comparable to avoid
duplicate entries in the database. For ease of data entry, it
must be possible to make a copy of an existing Motorcycle.
Your contribution to this project is to design and implement
a class named Motorcycle that will represent a single
Motorcycle.
01/07/16

29

Designing a Motorcycle Class:


Behaviors/Services
After reading the problem description, the
following behaviors/services have been
identified for the Motorcycle class.
Create a Motorcycle with a VIN, color, date of
arrival, and date of sale.
Compare two Motorcycle objects to determine if
they are identical.
Format a string containing all Motorcycle
attributes.
Create a new Motorcycle which is the copy of an
existing Motorcycle.
01/07/16

30

Designing a Motorcycle Class:


Instance Variables
To support the required services, a simple
Motorcycle class could contain instance
variables representing each of the Motorcycles
required class members.
These instance variables would all be class types:
name of type String, and two dates of type Date.
As a first line of defense for privacy and to
provide proper encapsulation, each of the
instance variables would be declared private.

01/07/16

31

Designing a Motorcycle Class:


Constraints
In order to exist, a Motorcycle must have (at
least) a VIN, color, and a Date of arrival.
Therefore, it would make no sense to have a noargument Motorcycle class constructor.

A Motorcycle that has not been sold does not yet


have a date of sale.
Therefore, the Motorcycle class constructor will need to
be able to deal with a null value for date of sale (and/or
provide a 3 argument constructor).

A Motorcycle that has been sold must have had


an arrival date that preceded its date of sale.
Therefore, when both dates are provided to the
constructor, they will need to be checked for validity.
01/07/16

32

Designing a Motorcycle Class:


The Class Invariant
A statement that is always true for every object of the
class is called a class invariant.
A class invariant can help to define a class in a consistent and
organized way

For the Motorcycle class, the following should always


be true
An object of the class Motorcycle has a VIN, color, a date of
arrival (which are not null values), and if the object has a date
of sale, then the date of sale is equal to or later than the date
of arrival.

Checking the Motorcycle class confirms that this is


true of every object created by a constructor, and all
the other methods (e.g., the private method
isValidState) preserve the truth of this statement.
01/07/16

33

Class Invariant Summary


The class invariant is stated as part
of the class documentation.
Error checking in the constructor(s)
and accessors/mutators insure that
the class invariant is not violated.
Methods of the class which do not
change the classs state may assume
the class invariant holds.
01/07/16

34

A Motorcycle Class
Constructor

01/07/16

35

Checking the Class


Invariant

Which part of the invariance are we


validating?
01/07/16

36

Composition
Note that the Motorcycle class contains two
class type instance variables (String and Dates).

The use of classes as instance variables is a


design method known as aggregation or
composition.
Composition is a fundamental way to reuse
code, but there are coding considerations when
composition is used.
01/07/16

37

Composition
Considerations

With composition, Motorcycle becomes


a user of the Date and String classes.
The Motorcycle class has no special
privileges with respect to Date or String.
The Motorcycle class should delegate
responsibility to the Date and String
classes whenever possible.
We let each class do the work of that
object.

01/07/16

38

Designing a Motorcycles
Class: The equals Method
The definition of equals for the class Motorcycle
includes an invocation of equals for the class
String, and an invocation of the method equals
for the class Date.
The Motorcycle class passes responsibility for
determining equality to the String and Date
classes invoking their equals methods.
This is an important example of code reuse arising from
the use of composition to implement Motorcycle.

Java determines which equals method is being


invoked from the type of its calling object.
01/07/16

39

Designing a Motorcycles
Class: The equals Method

Warning Potential Statement of Mass


Destruction!
Consider our Class Invariant

01/07/16

40

Designing a Motorcycle Class:


The toString Method
The Motorcycle class toString method includes
invocations of the Date class toString method.
Again, an example of code reuse and delegation
of responsibility due to composition.

01/07/16

41

Designing a Motorcycle Class:


Making a Copy
Making a copy of an object requires a
special method called a copy constructor.
A copy constructor is a constructor with a
single argument of the same type as the
class.
The copy constructor should create an
object that is a separate, independent
object, but with the instance variables set
so that it is an exact copy of the argument
object.
01/07/16

42

Copy Constructor for a Class


with Primitive Type Instance
Variables

01/07/16

43

Copy Constructor for a Class


Using Composition
Because of composition, the technique
used with Date will not work correctly with
Motorcycle in its current form

01/07/16

44

Copy Constructor for a Class


with Class Type Instance
Variables

The actual copy constructor for the Motorcycle


class needs to be made safe.
Should create completely new and independent copies
of arrived and sold, and therefore, a completely new
and independent copy of the original Motorcycle object
For example:

Note that in order to define a correct copy constructor


for a class that uses composition, copy constructors
must already be defined for the instance variables
classes (e.g. Date).
01/07/16

45

Copy Constructor for a Class


Using Composition

Why do we not have to invoke a copy constructor with


vin and color?
Strings are immutable objects.

Why is it necessary to check to see if other == null ?


A null pointer exception will occur if other is not an
instantiated Motorcycle object.
01/07/16

46

Using and Misusing


References
When writing a program, it is very
important to insure that private instance
variables remain truly private.
For a primitive type instance variable, just
adding the private modifier to its
declaration should insure that there will be
no privacy leaks.
For a class type instance variable, adding
the private modifier alone is NOT
sufficient.
01/07/16

47

Pitfall: Privacy Leaks


The previously illustrated examples from the
Motorcycle class show how an incorrect definition
of a copy constructor can result in a privacy leak.
A similar problem can occur with incorrectly
defined mutator or accessor methods.

01/07/16

48

Composition with Arrays


Just as a class type can be used as
an instance variable, arrays can also
be used as instance variables.
We can define an array with a
primitive base type.
Or, an array with a class base type.

01/07/16

49

Privacy Leaks with Array


Instance Variables

If an accessor method is provided for the


array, special care must be taken just as
when an accessor returns a reference to
any private object.

The example above will result in a privacy


leak.
WHY???
01/07/16

50

WHY Privacy Leaks Here?


The previous accessor method would simply
return a reference to the array grades itself.
DANGEROUS!!! The array grades can be modified
without restriction in this case!

Instead, an accessor method should return a


reference to a deep copy of the private array
object.
Below, grades is an array which is an instance
variable of the class containing the getGrades
method.

01/07/16

51

WHY Privacy Leaks Here?


(Cont.)

If a private instance variable is an array that


has a mutable class as its base type, then
copies must be made of each class object in
the array when the array is copied.

01/07/16

52

But What If
the user really wants to change the
array within the class?
The user shouldnt know that the class
uses an array.
The array must represent some abstract
data element in the class (e.g. student
grades).
Provide a method that changes the
abstract data element without revealing
the existence of an array.
01/07/16

53

Remember

01/07/16

54

Vous aimerez peut-être aussi