Title: Classes
1Classes
2Introduction
- Composite Data Structures
- Abstract Data Types and Object-Oriented Design
- Classes
- Client Program
- Object-Oriented Design Using Nouns and Verbs
- Improvements to the Time Class
- UML Diagram of the Time Class
3Composite Data Structures
- Two common aggregate (or composite) data
structures in the Java language are arrays and
classes. - An array is designed to contain a collection of
items that all have the same type. - A class can contain elements that all have the
same type but typically will contain elements of
dissimilar types.
4- When might we use a class?
- Consider a Time object.
- A Time object may consist of the hour, minute and
second. - In conversation, we speak of the current time but
in reality we are referring to the current hour,
minute and second.
5- public class Time
- private int hour
- private int minute
- private int second
- //
- // end class Time
6- The keyword class indicates the data type is a
class. - Time is the new type name that we are creating
(similar to an int or float except that Time is a
user-defined type). - The elements or data members of type Time are
contained within the braces. - Each data member within the class Time is
preceded by its own type in this case all have
type int. - The keyword private means that only member
methods of the class (not yet shown) can change
the data members.
7- A data member type could be an array, e.g. an
array of int, or another class. - public class myClass
- private int i
- private myClass mc
- private anotherClass ac // Legal as long as
- // anotherClass has
- // been defined
- // elsewhere
8- Classes do not reserve any space in memory.
- They are nothing more than a user-defined data
type. - Memory is reserved when a program declares an
object of the user-defined data type.
9- To declare an instance (or object) of type Time
you would code - public class Time
- private int hour
- private int minute
- private int second
- //
-
- public class TimeTest
-
- public static void main(String args)
-
- Time time new Time() // Declare an
instance - // time of type Time
- // end main
- // end class TimeTest
10- The declaration of instance time causes enough
contiguous memory to be reserved to store the
address of the time object and the three integer
values hour, minute and second. - time
-
- hour minute second
-
- FFOO
FFOO
11Abstract Data Types and Object-Oriented Design
- Object-orientation is a natural way of looking at
our world. - It also allows for an easy transition to
facilitate writing programs.
12- As you drive through your city, you see objects
all around you--cars, buildings, traffic lights,
people, babies, etc. - You categorize and identify them by their
attributes and behaviors. - If I asked you, "What has four legs, fur, a tail
and barks?" you would most likely answer, "A
dog." - Attributes four legs, fur, a tail
- Behavior barks
13- Objects may also communicate between each other.
- A person object may communicate to a dog object
by giving it a command such as "Fetch." - A car responds to the changing colors of a
traffic light. - In object-oriented terminology, this is referred
to as messaging.
14- In this world, there are many dogs, e.g. Lassie,
Benji, Rin Tin Tin, but they all exhibit the same
attributes and behaviors that put them into the
category of dog. - However, each of those dogs is a unique instance
of the category of dog. - In object-oriented terminology, we refer to
Lassie as an object (or instance) of the class
dog, Benji as an object (or instance) of the
class dog, etc.
15- A primary goal of object-oriented design (OOD) is
to identify classes using attributes and
behaviors. - A class, also known as an abstract data type
(ADT), is an abstract description of a
user-defined data type. - It is a description of the attributes (data
members) of the data type and the operations
(member methods) that can be performed on those
data members.
16- After the classes are identified and defined, the
next step is to look for class relationships
where classes may be related to each other
through composition or inheritance.
17- Composition is referred to as the "has-a"
relationship. - Given two classes, car and radio.
- Each class has its own respective attributes and
behaviors. - Using the "has-a" test, a "car has a radio".
- Cannot say that "radio has a car" because that
doesn't make sense. - But "car has a radio" implies that radio is an
attribute of the class car.
18- Inheritance is referred to as the "is-a"
relationship. - A convertible is-a car.
- Convertible inherits all the attributes
(manufacturer name, model, etc.) and behaviors
(stop, start, turn left, turn right, etc.). - Convertible also has additional attributes and/or
behaviors that a car does not have (for example,
a convertible has a top that goes up and down). - The is-a test also tells us the parent (car) and
the child (convertible) in the inheritance
relationship.
19- OOD encapsulates data (attributes) and methods
(behaviors) into objects the data and the
objects are closely tied together. - A complex number has two attributes the real
value and the imaginary value. - Behaviors involving complex numbers might be
addition (adding real to real and imaginary to
imaginary), subtraction, multiplication,
comparison (equal, less than, greater than),
display and setting the values of the real and
imaginary parts.
20- In contrast, a fraction has two attributes the
numerator and the denominator. - Similar to a complex number, we can also add
fractions but fraction addition involves
converting two fractions so they have a common
denominator, adding the numerators and then
reducing the fraction.
21- Given two complex numbers, c1 and c2, perform
addition by coding c1.add(c2). - Addition for two fractions, f1 and f2, would be
coded the same way, i.e. f1.add(f2), but the
addition process would be different than that for
complex numbers. - For display purposes, a complex number might be
printed in the format 3 4i whereas a fraction
would be displayed as 3/4. - The data (attributes) and methods (behaviors) are
encapsulated within the object. The behavior (or
method) that is invoked depends on what the
object is.
22- Classes provide the capability of information
hiding to hide the unnecessary details of a class
implementation from those who have no need or
desire to see them. - The implementation details are hidden from the
client programmer within the class.
23- "Methods" is an object-oriented term that is used
in lieu of the word "functions." - A method header provides
- The accessibility of the method (e.g. public or
private). - The method's return type.
- The name of the method.
- Method parameters (if any)
- Pre- and post-condition comments.
- This is referred to as the method interface.
24- The information contained in the method interface
should be all that is necessary for a client
programmer or another class object to invoke the
method contained within the class. - A good analogy for information hiding is that it
is possible to drive a car as long as the driver
is familiar with the car's interface (key or
ignition system, steering wheel, automatic
transmission lever, accelerator pedal and brake
pedal). - The driver does not need to know the details of
how the electrical, engine and transmission
systems work in order to drive the car.
25Classes
- We will now create a class for the abstract data
type Time. - Use public and private member access specifiers
to guarantee that the data members hour, minute
and second will never contain invalid values. - Our class declaration for Time will look like the
following slide
26- // Time.java - maintains the time in 24-hour
format - public class Time
-
- private int hour // 0 - 23
- private int minute // 0 - 59
- private int second // 0 - 59
- public Time()
- // Post-condition 0 will be stored in hour,
minute, - // and second
-
- hour 0
- minute 0
- second 0
-
- public void setHour(int h)
- // Pre-condition h must be in the range 0 - 23
27- public void setMinute(int m)
- // Pre-condition m must be in the range 0 - 59
- // Post-condition m will be stored in minute if
valid - // otherwise 0 will be stored in minute
-
- if (m lt 0 m gt 59)
- minute 0
- System.out.println("Minute is not valid--will
be set to 0") -
- else
- minute m
-
- public void setSecond(int s)
- // Pre-condition s must be in the range 0 - 59
- // Post-condition s will be stored in second if
valid - // otherwise 0 will be stored in second
-
- if (s lt 0 s gt 59)
28- public void setTime(int h, int m, int s)
- // Pre-condition h must be in the range 0-23
and m and s must be in the range 0 - 59 - // Post-condition if valid, h, m and s will be
stored in hour, minute and second, respectively - // otherwise 0 will be stored in the respective
data member -
- setHour(h)
- setMinute(m)
- setSecond(s)
-
- public String toUniversalString()
- // Pre-condition None
- // Post-condition converts to String in
universal time format (HHMMSS) -
- return String.format("02d02d02d", hour,
minute, second) -
- public String toString()
- // Pre-condition None
29- A Time object has attributes (or data members)
hour, minute and second. - From a behavior standpoint, we would also like to
be able to store values into hour, minute and
second (among other behaviors such as value
retrieval). - We encapsulate within the Time class the data
members hour, minute and second along with the
member functions to store legitimate values into
those data members.
30- One of the primary objectives of object-oriented
programming is to insure that all class data
members are in a safe state at all times. - Accomplished by using the member access
specifiers public and private. - Make the data members private by placing the word
private immediately before them. - Once a data member (or member function) is
declared private, the only items that can access
it directly are member functions of that class. - Public members can be accessed by the client
program, the class itself and other classes.
31- So then how can we store a value into Time's hour
if it is declared to be private? - We call a public member function that must
validate the value prior to storing it into the
private data member. - It is the responsibility of all member functions
of a class to guarantee that no invalid value
will ever be stored in the class's data members.
32- Too many times, a programmer creates a class and
then either - makes the data members public or
- does not put error checking code into any of the
methods that can store values in the data
members. - One of the primary objectives of object-oriented
programming is to guarantee that all data members
are kept in a safe state at all times. - This fact cannot be emphasized enough.
33- A standard programming practice is to place all
private date members first in the class
definition, followed by the public and private
member methods. - Another good programming practice is to make all
data members private. - Most methods will be public but a few utility
methods (methods used by the class but not by the
client program) will be private.
34- Mutator methods change the values stored in the
data members. - The public methods that store (or set values)
into the private data members are mutator
methods. - It is the responsibility of those methods to
guarantee that the data members will always
remain in a safe state.
35- An accessor method accesses the values contained
in the data members but does not change them. - The toString and toUniversalString methods are
accessor methods.
36- The following function prototype is a very
special one, known as a constructor . -
- Time()
- It does not have a return type.
- Its name is the same name of the class.
- Its purpose is to initialize the values of the
data members to a safe state.
37- As a programmer, you typically do not call the
constructor explicitly it is invoked implicitly
when an object of the class is declared. - public static void main(String args)
-
- Time lunchTime new Time()
-
- The statement, Time lunchTime new Time()
- Invokes the constructor Time()
- Reserves space in memory for the lunchTime
object.
38- The constructor Time() is called the default
constructor because it does not require any
arguments. - If you do not code a default constructor
- The compiler will automatically provide one
- It will not guarantee proper initialization of
the class's data members. - You should always code your own constructor to
insure that the data members are initialized to a
safe state.
39- It is also possible to code other constructors,
either in lieu of the default constructor or in
addition to the default constructor. - These constructors (which have arguments) are
known as conversion constructors. - If a conversion constructor is coded but no
default constructor is present, the compiler will
not automatically provide a default constructor.
40- An example of a conversion constructor might be
- public Time(int h, int m, int s)
- // Pre-condition Arguments must be in the
- // following range
- // h (hour) 0-23
- // m (minute) 0 - 59
- // s (second) 0 - 59
- // Post-condition If an argument is out of
range, - // the respective data member will be set to 0
-
- setTime(h, m, s)
-
41Interface and Implementation Files
- To make code easier to read, it is sometimes
split between an interface file and an
implementation file. - The interface file contains the method prototypes
which are the only thing a client programmer
needs to utilize the class. - The interface file does not contain the
implementation code for the methods. - However, code must be provided for the method
prototypes specified in the interface file and
that is done within the implementation file.
42- If we split the code in the prior example into an
interface file and an implementation file, the
only change to Time.java would be to replace the
statement - public class Time
- with the statement
- public class Time implements TimeInterface
- The interface file would look like the following
file
43- // TimeInterface.java - Interface file for the
Time class - public interface TimeInterface
-
- public Time()
- // Post-condition 0 will be stored in hour,
minute, - // and second
-
- public void setHour(int h)
- // Pre-condition h must be in the range 0 - 23
- // Post-condition h will be stored in hour if
valid - // otherwise 0 will be stored in hour
-
- public void setMinute(int m)
- // Pre-condition m must be in the range 0 - 59
- // Post-condition m will be stored in minute if
valid - // otherwise 0 will be stored in minute
-
- public void setSecond(int s)
44- Though hour, minute and second are declared
private within the class declaration, all member
functions of the Time class have access to the
data members and can store and retrieve values
from them. - The private protection extends only to any code
beyond the class itself. - A client program that uses the class would not be
able to store values directly into the data
members. - It would need to invoke the public member
functions to store any values.
45Client Program
- Client programs are those programs that invoke
the methods contained within the class(es). - Typically, client programs are the programs that
contain the main() function.
46- An important item to note here is that when
designing and writing the code for a class, the
code should be written so that any client program
can use the class. - A key to object-oriented programming is
reusability. - Class code ideally should be able to be used by
any number of client programs. - A sample client program that uses the Time class
might look like the following slide
47- public class TimeTest
-
- public static void main(String args)
-
- Time lunchTime new Time() // Object
lunchTime with hour, - // minute and second set to 0
- Time dinnerTime new Time() // Object
dinnerTime with hour, - // minute and second set to 0
- System.out.print("Lunch time is ") // Display
lunch time - System.out.println(lunchTime.toUniversalString()
) - System.out.print("Dinner time is ")// Display
dinner time - System.out.println(dinnerTime.toUniveralString()
) - lunchTime.setHour(12) // Set lunchTime hour to
12 - lunchTime.setMinute(15) // Set lunchTime
minute to 15 - lunchTime.setSecond(30) // Set lunchTime
second to 30 - System.out.print("Lunch time is ") // Display
lunch time - System.out.println(lunchTime.toUniversalString()
)
48- The following would be displayed in the console
window when the client program is executed - Lunch time is 00000
- Dinner time is 00000
- Lunch time is 121530
- Second is not valid--will be set to 0
- Dinner time is 182000
- Dinner time in standard format is 62000 PM
49- When lunchTime is declared, sufficient contiguous
space is reserved in memory to store three
integer values hour, minute and second. - Similarly, when dinnerTime is declared, space is
also reserved for dinnerTime's hour, minute and
second. - At the time of declaration of lunchTime and
dinnerTime, the constructor for each object is
called to initialize the integer values contained
in memory.
50- After lunchTime and dinnerTime are declared and
initialized, the two objects are considered to be
in a "safe state," i.e. they do not contain
garbage or any illegitimate values. - After declaration, the objects stored in memory
will look like the following slide - For the ease of diagramming, the labels lunchTime
and dinnerTime are displayed belowthe hour,
minute and second fields in the diagram. - Technically, lunchTime and dinnerTime contain the
address of where lunchTime and dinnerTime are
located in memory as was diagrammed in a prior
slide.
51- hour minute second
- lunchTime
- hour minute second
- dinnerTime
0
0
0
0
0
0
52- When calling the function setHour, the statement
is - lunchTime.setHour(12)
- Though it looks like the function setHour is only
being called with one argument, the value 12, in
reality the function is being called with two
arguments lunchTime and the value 12. - The object that precedes the dot operator is
called the implicit argument. - Any arguments that are between the parentheses
are called the explicit argument(s).
53- hour minute second
- lunchTime
- hour minute second
- dinnerTime
12
15
30
0
0
0
54- The program attempts to assign the value of 80 to
dinnerTime's data member second. - The setSecond function displays an error message
that the 80 is an invalid value for second and
stores the value of 0 into the data member
second. - It would be nice if the set function could
reprompt the user for the correct value but many
times, client programs do not directly interface
to a user they may be working with file
input/output for example. - An error message is displayed and a predetermined
default value is assigned.
55- hour minute second
- lunchTime
- hour minute second
- dinnerTime
12
15
30
18
20
0
56- Though hour, minute and second are declared
private within the class declaration, all member
functions of the Time class have access to the
data members and can store and retrieve values
from them. - The private protection extends only to any code
beyond the class itself. - A client program that uses the class would not be
able to store values directly into the data
members. - It would need to invoke the public member
functions to store any values.
57Object-Oriented Design Using Nouns and Verbs
- Suppose you were given the following problem
specification - Military time consists of hour, minute and
second based on a 24-hour clock. Your abstract
data type time should be able to independently
set the hour, minute and second as well as
display the time in military format hhmmss.
58- Programmers use the noun-verb classification to
help them identify class names, data members and
member functions (or methods). - When reading the problem specification, circle
the nouns and underline the verbs.
59- Using the above example, we have
- Nouns Verbs
- time consists (has-a)
- clock set
- hour display
- minute
- second
60- Nouns will either indicate your class names, data
member names or be disregarded. - Verbs will indicate your functions.
- As we look at the nouns, time appears to be more
significant than the other nouns. - Consider it as a potential class name.
- Hour, minute and second are not significant
enough to warrant their own classes. - Because of the has-a relationship which
indicates composition, we can say that the class
Time has data members hour, minute and second. - Clock is also a noun but can be disregarded.
61- The verb consists translates into the has-a
relationship. - The verb set is used in the context set hour, set
minute and set second. - The verb (sometimes used in conjunction with a
noun) provides a good name for our class
functions, in this case setHour, setMinute and
setSecond. - Our final verb, display is sufficient enough for
its own function name or could be combined with
the word time to get displayTime.
62Improvements to the Time Class
- Our Time class has the ability to independently
set the data members but a client program cannot
retrieve the values contained in hour, minute and
second. - Perhaps I wish to write a client program that
will create two objects, lunch time and dinner
time and also determine the time difference
between the two times. - As the Time class exists now, I would be unable
to do that.
63- Basic components of a class are
- constructor(s)
- set (mutator) functions
- get (accessor) functions
- any other functions the class might need.
- By modifying the Time class to the following
slides, we make our class more versatile.
64- // TimeInterface.java - Interface file for the
Time class - public interface TimeInterface
-
- public Time()
- // Post-condition 0 will be stored in hour,
minute, - // and second
-
- public void setHour(int h)
- // Pre-condition h must be in the range 0 - 23
- // Post-condition h will be stored in hour if
valid - // otherwise 0 will be stored in hour
-
- public void setMinute(int m)
- // Pre-condition m must be in the range 0 - 59
- // Post-condition m will be stored in minute if
valid - // otherwise 0 will be stored in minute
-
- public void setSecond(int s)
65-
- public int getMinute()
- // Pre-condition None
- // Post-condition minute will be returned
- public int getSecond()
- // Pre-condition None
- // Post-condition second will be returned
- public String toUniversalString()
- // Pre-condition None
- // Post-condition converts to String in
universal time format (HHMMSS) -
- public String toString()
- // Pre-condition None
- // Post-condition converts to String in
Standard time format (HMMSS AM or PM) - // end interface TimeInterface
66- // Time.java - Implementation file for the Time
class - public class Time implements TimeInterface
-
- private int hour // 0 - 23
- private int minute // 0 - 59
- private int second // 0 - 59
- public Time()
- // Post-condition 0 will be stored in hour,
minute, - // and second
-
- hour 0
- minute 0
- second 0
-
67- public void setSecond(int s)
- // Pre-condition s must be in the range 0 - 59
- // Post-condition s will be stored in second if
valid - // otherwise 0 will be stored in second
-
- if (s lt 0 s gt 59)
- second 0
- System.out.println("Second is not valid--will
be set to 0") -
- else
- second s
-
- public int getHour()
- // Pre-condition None
- // Post-condition hour will be returned
-
- return hour
-
68- public String toUniversalString()
- // Pre-condition None
- // Post-condition converts to String in
universal time format (HHMMSS) -
- return String.format("02d02d02d", hour,
minute, second) -
- public String toString()
- // Pre-condition None
- // Post-condition converts to String in
Standard time format (HMMSS AM or PM) -
- return String.format("d02d02d", ((hour
0 hour 12) ? 12 hour 12), - minute, second, (hour lt 12 ? "AM" "PM"))
-
- // end class Time
69UML Diagram of the Time Class
- A class, its data members and member functions
can be diagrammed using the Unified Modeling
Language (UML) notation.
70- The class diagram consists of three parts
- The top section is the class name.
- The middle section contains the class's data
members. - The bottom section contains the member functions.
- If a class member is preceded by the symbol , it
means that the class member is public. - A minus symbol (-) indicates the class member is
private.
71Time
- hour int - minute int - second int
ltltconstructorgtgt Time() setHour(int h)
void setMinute(int m) void setSecond(int s)
void getHour() int getMinute() int
getSecond() int toString() String
toUniversalString() String