Title: Chapter 10: More on Classes
1Chapter 10 More on Classes
- Here, we look in more detail at the design and
use of classes - Much of this chapter will only be briefly
highlighted as the contents are more appropriate
for CSC 262 - But we will examine visibility modifiers, static
members and the this reference here - We will try to obtain a better idea of
information hiding as this is a very important
idea - We will only briefly introduce inheritance and
related topics - And then we will focus on the idea of an array of
objects and see how we might implement use them
2Visibility Modifiers revisited
- Recall from chapter 9 that we noted that entities
in a class can be defined as public or private - Now we can get a better feel for what these mean
- public is used to define the class interface
- The interface is how other objects will
communicate with this object - The interface should be limited to only those
things that another object should have access to - This will be those methods and data that are
provided for external usage - private is used to define class entities that
should be protected - Instance data should always be private
- Methods that are only used internally should be
private, methods that are to be called from other
objects should be public - Recall the Rational class that we examined from
chapter 9, gcd( ) and reduce( ) were two methods
that were only called from inside, and so these
methods were made private
3The static Modifier
- static, as used in Java, is meant to convey that
this defined item can be used independently of
any specific object - The static methods that we had previously written
in the program with the main method meant that
you did not need to first instantiate an object
of the class to call any of those methods - If we choose to make a method static, it can then
be called by specifying the class itself rather
than an object as in Math.sqrt() - We can also make instance data static
- This results in having a single instance of the
instance data, shared by all objects - There are few reasons to make instance data or
methods static and we are only forced to do this
if the class has a main method - The book offers an example where all Employee
objects variable taxRate see pages 381-382
4The this Reference
- this is a reference to this object
- We can use this if code inside the object must
refer to the object itself - The simplest example occurs in a constructor
where we want to reference this objects instance
data rather than a parameter
public class ThisExample private int
x private int y public
ThisExample(int x, int y) this.x
x this.y y
By using this.x, the Java compiler knows that the
left-hand variable is the instance data x in the
class and the right-hand variable is the parameter
The this reference is not needed in most cases
although it is very useful when implementing
applets
5Inheritance
- One of the strengths of object-oriented
programming is the ability to define a class as
being an extension of a previous class - The new class is a subclass
- The previous class is the parent class
- The subclass inherits everything from the parent
class so that the subclass is building on top of
what was previously written - Consider that I write a Window class
- You extend it to be a WordProcessorWindow class
- Someone else extends your WordProcessorWindow
class to be a WordProcessorWithGraphicsWindow
class, etc
6Controlling Inheritance
- All classes in Java have a single parent
- If no parent is specified, Java defaults the
parent to Object - Note Java does not allow a class to have
multiple parents, unlike C and other OO
languages - To extend a class, use the term extends class
as in - public class GradStudent extends Student
- To specify what aspects of a parent class can be
inherited, use visibility modifiers - public available to all classes
- private available to no outside classes
- protected available to no outside classes
except for extended classes (subclasses) - We will cover this in much greater detail in CSC
262, here we will skip a majority of chapter 10
(10.3-10.4)
7Arrays of Objects
- There is no restriction on the type of item
stored in the array - Earlier we saw arrays of integers, floats, chars
and Strings - Strings are objects
- We can similarly store other objects in an array
- Define your class, such as exampleClass
- Create an array of exampleClass, such as
arrayExampleClass - Create an instance of arrayExampleClass
- We will develop an example momentarily
8Example Array of CDs
- We previously defined an object that stored an
array, now we will create a class and then define
an array of objects of that class - Consider a CD Library
- Each CD has certain attributes or values such as
group name, CD title, price, number of songs - We create a class called CD with these data
instances - The class will need a constructor, a toString
method and methods to access a given CDs
information - Since the constructor receives parameters that
are the values of the group name, CD title, price
and number of songs, we dont need methods to
change these values once the CD has been created - CD class follows on the next slide
9CD Class
import java.text.NumberFormat public class CD
private String artist, cdTitle
private double cost private int
numSongs public CD(String name, String
title, double price, int num) artist
name cdTitle title cost price numSongs
num public String getArtist( )
return artist public
String getTitle( ) return
cdTitle
public double getCost( ) return
cost public int getNumberOfSongs( )
return numSongs public
String toString( ) NumberFormat
nf NumberFormat. getCurrencyInstance( )
return artist "\t" cdTitle "\t"
nf.format(cost) "\t" numSongs
10CD Library
- Now that we have a class, CD, we will use it to
create a collection of CDs, or an array of CDs - We define a new class, CDCollection
- It contains at least two items
- CD collection collection is the array of CD
objects - int count the number of items currently in the
collection - We could also keep track of
- totalValue (the total cost of all CDs in the
collection) - numberOfArtists (the total number of different
artists) - The class will have methods to
- Construct the collection object
- Add a CD to the array
- Print out the entire CD collection
- Find a specific CD and print out its information
or remove it from the collection (delete it) - Find all of the CDs by a specific artist
11The CD Library Class
A partial definition public class CDLibrary
private CD collection private
int size public CDLibrary( )
collection new CD100 size 0
public CDLibrary(int maxSize)
collection new CDmaxSize size 0
other methods here
Notice two constructors, one that sets the array
size to 100 and one that sets the array size to
whatever we want it to be initially We could add
a totalValue variable and other instance data if
we want, but we wont bother in this example
12Adding a CD
- Here we see a method to add a new CD
- All it does is make sure that there is still room
in the array and then adds a newly constructed CD
to the first freely available location
public void addCD(String title, String artist,
double value, int tracks) if (count lt
currentSize)
collectioncount new CD(title, artist, value,
tracks) count else
System.out.println("Cannot add new CD array
full")
calls CD constructor to create new CD object
add the new CD at the first free location (which
is at position count)
Increment count to point to the next free
location in the array
13How addCD Works
Count 3, we have elements in locations
0-2 Our next entry will be added to 3
and then we increment Count to 4 What if
Count 99, we cannot add something to
element 100! We could add an increaseSize(
) method which creates a new array twice the
size of the current array, and copies the old
array into the new one, now we have room to add
the new CD
Count 3 0 1 2 3 4
99
CD CD CD Object 1 Object 2 Object 3
14The searchGroup Method
public void searchGroup(String target)
int i, matches 0 System.out.println("Sear
ching for CDs by " target)
for(i0iltcounti) if(collectioni.getArtis
t( ).equals(target))
System.out.println(collectioni)
matches System.out.print("Number of
CDs from " target) System.out.println("i
s " matches)
- Here, we have a method that searches for all CDs
by a given artist - If there is a match, the CD is output and we add
1 to matches, counting the number of CDs by this
artist
Note this calls CDs toString( ) method
Lets examine collectioni.getArtist(
).equals(target) collectioni is an
element of collection, so it is a CD
collectioni.getArtist( ) passes the message
getArtist( ) to the CD object the CD object
will return the artists name
collectioni.getArtist( ).equals(target)
compares this name to the String target, and is
either true or false
15A deleteCD Method
- This method searches for the CD that matches both
artist and title, and once found, deletes it in a
similar way to deleting an int from an int array
public void deleteCD(String artist, String
title) int i, j, location -1
for(i0iltcounti)
if(collectioni.getArtistName( ).equals(artist)
collectioni.getTitle( ).equals(title))
location i if(location -1)
System.out.println("CD not found! ") else
collectionlocation
collectioncount-1 count--
System.out.println("CD deleted ")
We move the last CD into the deleted CDs place
and then subtract 1 from count thus making the
array 1 fewer (in fact, the last CD now is
stored twice, but we never access the last one
since count is now 1 fewer
16Find a CD
If we want to find a specific CD for some reason
(for instance, to see how much it cost), we use
much the same strategy as the deleteCD method
but instead of deleting the CD once found, we do
something else Here, once found, we just print
out the CDs information
public void findAndPrintCD(String artist, String
title) boolean found false
int i 0 while(!found i lt count)
if(collectioni.getArtist(
).equals(artist) collectioni.getTitle(
).equals(title)) found true
else i if(found) System.out.println(co
llectioni) else
System.out.println("CD not found!")
Once the CD is found, we could also allow the
user to update/change some of its values creating
an updateCD method
17CD Collection User Class
- Now we must define a CD Collection User class
- In essence, CD Collection represents a database
of CDs - The CD Collection User is the interface with the
user - The user will want to control the CD Collection
class by specifying things like - I want to add a CD
- I want to find all CDs by artist X
- I want to delete a CD
- I want to print out the entire collection
- This class will create an object of type
CDCollection - It will then use a menu-driven approach to allow
the user to input a command (add, find artist,
delete, print, etc) and pass a message to the
appropriate CDCollection method - A complete example of this database is given on
the web site
18Common Errors
- Mis-declaring class members (data members or
member functions) to the wrong visibility type - Making data members public
- Making methods that should be called from outside
private - Not making data members or member functions
protected if they should be inherited - Misusing static in general, dont use it unless
you are defining methods along with your main
method - Not making an array large enough to store all
the necessary entities - Forgetting to modify number/count which denote
the number of items stored in your array when
adding or deleting