Chapter 9: Classes - PowerPoint PPT Presentation

1 / 26
About This Presentation
Title:

Chapter 9: Classes

Description:

if I had a car object with age and odometer value ... If I want to know if a car, car1, is worth buying, I might want to know it's age, ... – PowerPoint PPT presentation

Number of Views:20
Avg rating:3.0/5.0
Slides: 27
Provided by: foxr
Category:
Tags: chapter | classes

less

Transcript and Presenter's Notes

Title: Chapter 9: Classes


1
Chapter 9 Classes
  • To this point, we have used previously written
    classes to accomplish various tasks
  • Math to perform mathematical operations
  • JOptionPane for GUI input and output
  • BufferedReader for non-GUI input
  • DecimalFormat, NumberFormat to format
    float/double output
  • Date to get todays date
  • But otherwise, we have yet to really see what a
    class is
  • In this chapter, we introduce the elements that
    make up a class and write a few basic ones of our
    own
  • In the next chapter, we will explore classes
    including arrays of classes (this material is not
    in the textbook) and aspects of classes that are
    covered in more detail in CSC 262

2
Object-Oriented Programming
  • The class is the central concept behind OOP
  • Rather than writing a program, you write a series
    of classes that interact with each other
  • This more closely models the real world
  • OOP further promotes modularity beyond what
    methods provide through the concepts of
    information hiding and encapsulation
  • The class represents a real class (category) of
    object in the world
  • Could be physical like a car, or conceptual like
    a window
  • The class itself consists of the data that
    describe the object
  • A car has a brand and model, year of
    manufacturing, a maximum speed, whether it is
    automatic or manual transmission, number of
    doors, etc
  • And the methods that operate on the data
  • Computing MPG, computing the value of the car,
    etc

3
Terminology
  • Class
  • the definition of the class that includes the
    data and the methods
  • Object (or instance or instantiated object)
  • A specific instance of a class with its own
    values for the data
  • Member functions
  • The methods that are available in the class
  • Data Members (also sometimes referred to as
    instance data)
  • The data that each object of the class will store
  • Data Members are usually invisible from outside
    of the class but accessible to the member
    functions in the class
  • Constructor
  • A special member function used to initialize data
    members when an object is first instantiated
  • Objects of the same class share member functions
    but each has its own data members (that is, the
    data can differ between objects)

4
More Terminology
  • Encapsulation
  • Combining the data members and member functions
    so that the entire class definition is
    self-contained
  • Some languages do not enforce encapsulation
  • That is, the definition of these items does not
    have to be self-contained
  • Information Hiding
  • Protecting the object from an external object by
    only allowing the object to be manipulated
    through its member functions
  • if I had a car object with age and odometer value
  • no one should be able to arbitrary change age or
    odometer on me
  • these values are only accessible through methods
    defined in the car class
  • such as add 1 year to age and add 10,000 miles
    to odometer
  • Information Hiding is maintained using the
    visibility modifiers public and private this
    will be addressed in chapter 10

5
Message Passing
  • Message Passing
  • How objects communicate to each other
  • A message is a method call
  • but where the method is part of another object,
    not the current object
  • example df.format(x) tells the
    DecimalFormat object df to format the parameter x
  • We have already seen message passing because we
    have used it to communicate with objects that we
    have used
  • JOptionPane, Math, and objects of types
    DecimalFormat, NumberFormat, BufferedReader,
    Random
  • Through message passing, we are able to have an
    object do something for us such as
  • change a value stored in a data member
  • compute something
  • report (return) a result

6
Message Passing
Object Data instances d1 d2 d3 Methods m1 m2 m3
m4
Program that uses object object.m1(
) object.m2( )
A program creates an instance of the object
and Then passes that object message (the name of
a method) The method manipulates the objects
data instances
Typically, the data instances are not visible
outside of the object and can only be accessed
through the objects interface, which are the
methods that are visible
7
Defining a Class
  • A class definition is much like our previous
    programs
  • it will consist of a series of methods
  • However, our classes
  • will have no main method
  • Instead, the methods will be called by other
    classes, perhaps a main method
  • will not (usually) have to have static methods
  • will include data members
  • to this point, all variables in our methods have
    been local variables or parameters, this is a
    third type of variable
  • will represent real-world classes and will
    therefore have methods and data members that
    model the real-world

8
Lets Build a Class
  • We consider to begin with a basic class, a Die
    (as in one of a pair of dice)
  • The die will have a couple of data
  • How many sides does the die have (6-sided?
    20-sided?)
  • What the current value of the die is
  • We could probably come up with other data, but
    these will suffice
  • The die will have a few methods
  • Constructor
  • rollDie operation
  • reportValue operation

9
Die Class
  • Here we see a definition for our Die class and a
    class that uses the Die class once it has been
    defined

import java.util.Random public class Die
private int numSides private int value
public Die(int size) // constructor
value 0 numSides size
public int getValue() // used to return
return value // the dies value
public int rollDie() Random
generator new Random( ) value
Math.abs(generator.nextInt( )) numSides 1
return value // assume this
file is called Die.java
import Die public class DiceStats public
static void main(String args) Die die1,
die2 int i, roll die1 new Die(6) die2
new Die(6) for(i0ilt50i)
roll die1.rollDie( ) die2.rollDie( )
System.out.println("Roll
is " roll)
10
Comments on the Die Class
  • The Die class has two data members
  • value the current value that the die is showing
  • numSides the number of sides of the die
  • Notice that the two data members are defined as
    private we will cover that next
  • And 3 methods
  • Die(x)
  • the constructor which initializes the two data
    members setting the Dies numSides to the
    parameter x, and value to 0
  • rollDie( )
  • which randomly generates a value that indicates a
    roll of the die
  • getValue( )
  • which returns the value shown on the die
  • why is getValue needed?
  • We already return the value in rollDie, so why
    should we write a method that merely returns a
    datum?

11
Comments on the DieStats Class
  • The DieStats class is much like our previous
    classes have been
  • It has a main method
  • It imports a class to use (Die)
  • This differs from importing java.text.DecimalForma
    t and javax.swing.JOptionPane how?
  • It creates instances of this class
  • DieStats creates two instances of Die
  • die1 and die2
  • It calls Dies constructor and rollDie methods to
    use die1 and die2
  • Notice that when constructing die1 and die2, we
    pass 6 as a parameter to indicate the size of the
    die
  • What would be the difference in DieStats if
    instead we did
  • die2 new Die(12)

12
Visibility Modifiers
  • A brief introduction (with respect to the Die
    class)
  • To this point, we have made our methods public
  • But, when defining a class, we can decide to make
    any method or data member
  • public available (accessible) to any other
    class
  • private available only inside of this class
  • If we had chosen to make rollDie private
  • then we could not pass the message die.rollDie( )
    from DieStats because rollDie( ) would be
    unavailable
  • If we had chosen to make value public then
    DieStats
  • could have directly changed value without rolling
    the Die, such as die1.value 1 which violates
    the idea that to use the Die, I have to use it
    through the available methods
  • For now, just make all methods public and all
    data members private, we will cover visibility
    modifiers in more detail in chapter 10

13
Class Constructors
  • We now concentrate in detail on writing a class
  • The class constructor is the mechanism whereby a
    classs object is initialized
  • If your class has data members that should have
    initial values, this is where they are assigned
  • initial values might include initializing sums to
    0
  • or, in the Die class, we initialized the number
    of sides of the die by a value passed in as a
    parameter
  • You do not need to provide a constructor as Java
    has a built-in default constructor, but it is
    always good to provide one because you can tailor
    your constructor

14
Overloaded Constructors
  • Recall that Java allows you to provide multiple
    methods that share the same name but have a
    different number of or type of parameters
  • This is know as overloading
  • Constructors can also be overloaded
  • This allows you to build different constructors
    based on what you might expect the user to
    provide
  • we could overload Dies constructor by supplying
    a second constructor that does not receive the
    number of sides of the die
  • in which case, we would initialize numSides to 6
  • think of this as the default constructor

public Die( ) Die d1 new Die(12) // d1 is
12-sided Die d2 new Die( ) // d2 is
6-sided value 1 numSides 6 //
default value
15
Example Date Class
  • The Date class will store a Dates information
  • Month
  • Date
  • Year
  • All will be int values as in 1 / 13 / 2003
  • What constructors should it have?
  • Lets provide one that receives the three values
    as int parameters, one that receives no values
    (we will then set the date to today, assuming
    today is 1/13/2003) and one that receives the
    date as a String written as //

public class Date public Date(int a, int b,
int c) private int month, date,
year month a date b year c
public Date( ) public
Date(String x) month 1 date
13 year 2003 // see next slide
16
Date Class Continued
public void advanceDate( ) date
if(date gt 28 month 2)
month date 1 else if
(date gt 30 month 4 month 6
month 9 month 11)
month date 1 else if
(date gt 31) month date 1 if
(month 13) month 1 year

public Date(String x) String s1
x.substring(0, 2) String s2
x.substring(3, 2) String s3
x.substring(6, 2) month
Integer.parseInt(s1) date
Integer.parseInt(s2) year 2000
Integer.parseInt(s3) public void
setDate(int newMonth, int newDate, int newYear)
month newMonth date
newDate year newYear public
void setDate( ) System.out.println(mo
nth "/" date "/20" year)
17
Class Methods Mutators, Accessors, Constructors
  • We have already mentioned Constructors
  • Methods that initialize an object
  • In addition, a class will require methods to
  • Access a data member to return the value so that
    it can be used elsewhere
  • These are known as accessor methods
  • Allow values stored in data members to be
    updated/altered
  • These are known as mutator methods
  • Example recall the Car class mentioned
    previously
  • If I want to know if a car, car1, is worth
    buying, I might want to know its age, but if age
    is private, then I have to request the age from a
    member function of Car as in
  • car1.getAge()
  • If I want to update car1s age, I might do it by
  • car1.increaseAge(numYears)

18
Complete Example
  • Lets model an elevator in a building
  • What data members will the elevator need?
  • The current floor
  • The number of floors that the building has
  • What methods will the elevator need?
  • A constructor
  • which is supplied with the number of floors of
    the building and initializes current floor to 1
  • we might have a default constructor (it receives
    no parameter) that assigns number of floors to be
    15 and initializes current floor to 1
  • Method to move the elevator up 1 or more floors
  • Method to move the elevator down 1 or more floors
  • Method to report where the elevator is
  • Method that takes a request and figures out what
    to do with the elevator

19
Elevator Class Code
public void goUp(int num) if(num
current lt numFloors)
for(int j0 jltnum j) up(
) report("waiting")
else System.out.println("Cannot meet request")
public void goDown(int num)
if(current num gt 1)
for(int j0 jltnum j)
down( ) report("waiting")
else System.out.println("Cannot meet
request")
public class Elevator private int
current private int numFloors
public Elevator(int f)
current 1 numFloors f
public Elevator( ) current
1 numFloors 15 public
void report(String command)
System.out.println("The elevator is currently on
floor " current " and " command)
20
Elevator Code Continued
import Elevator public class ElevatorUser
public static void main(String args)
Elevator e new Elevator(10)
e.request(6)
e.request(3) e.request(9)
e.request(10)
e.request(1) e.request(1) e.request(-5)

public void up( ) current
report("going up") public void
down( ) current-- report("going
down") public void request(int
requestFloor) int difference
requestFloor current if(difference
0) // do nothing, at the right location
else if(difference gt 0) goUp(difference) else
goDown(difference) // ends Elevator
class
This code uses the Elevator class to simulate
what happens as the Elevator moves up and down
the building
21
import java.text.NumberFormat public class
Account private NumberFormat fmt
NumberFormat.getCurrencyInstance( )
private final double RATE 0.045 private
String acctNumber private double balance
private String name public
Account(String owner, String account, double
initial) name owner account
acctNumber balance initial public
double deposit(double amount) if (amount lt
0) System.out.println("Error Deposit
amount is invalid") System.out.println(acctN
umber " " fmt.format(amount))
else balance amount
return balance
ExampleBank Account
22
public double withdraw(double amount, double
fee) amount fee if
(amount lt 0) System.out.println("Er
ror Withdraw amount " fmt.format(amount)
" is invalid for "AcctNumber ) else
if (amount gt balance) System.out.println(
"Error insufficient funds")
System.out.println(acctNumber " requested "
fmt.format(amount) " but only has "
fmt.format(balance))
else balance -amount return
balance public String getAccountNumber( )
public double addInterest(
) return acctNumber
balance (balance RATE)
return balance public String toString(
) return(acctNumber
" \t " name public double getBalance(
) " \t " fmt.format(balance))
return
balance
23
toString( ) Methods
  • Notice from the previous example the inclusion of
    a method called toString( )
  • What if we want to print out an object?
  • For instance, System.out.println(todaysDate)
  • Where todaysDate is an object of Date
  • Objects cannot be output directly as shown
  • But we can provide a class with this toString( )
    method which is called automatically if code
    attempts to print out an object of that class
  • So, if BankAccount x and we do
    System.out.println(x) then this is the same as
    System.out.println(x.toString( ))
  • that is, x is converted to a String and then this
    String is printed out
  • You decide what parts of the class should be
    placed in the String

24
Using the Account Class
import Account public class AccountUser
public static void main(String args)
Account acct1 new Account("Ted Murphy",
72354, 102.56) Account acct2 new
Account("Jane Smith", 69713, 40.00) Account
acct3 new Account("Edward Demsey", 93757,
759.32) acct1.deposit(25.85) double
smithBalance acct2.deposit(500.00) System.out.
println("Smith balance after deposit "
smithBalance) System.out.println("Smith balance
after withdrawal " acct2.withdraw(430.75,
1.50)) acct3.withdraw(800.00,
0.0) acct1.addInterest( ) acct2.addInterest(
) acct3.addInterest( ) System.out.println(acct
1) System.out.println(acct2) System.out.printl
n(acct3)
Calls Accounts toString( ) method
25
Rational Numbers
public class Rational private int
numerator, denominator public
Rational(int num, int denom) if (denom
0) denom 1 if (denom lt 1) num
num -1 denom denom -1
numerator num denominator
denom reduce( ) public Rational
add(Rational op2) int commonDenom
denominator op2.getDenominator( )
int num1 numerator op2.getDenominator( )
int num2 op2.getNumerator( )
denominator int sum num1 num2
return new Rational(sum, commonDenom)
public Rational subtract(Rational op2)
int commonDenom denominator
op2.getDenominator( ) int num1
numerator op2.getDenominator( ) int
num2 op2.getNumerator( ) denominator
int sum num1 - num2 return new
Rational(sum, commonDenom) public
Rational multiply(Rational op2) int
num numerator op2.getNumerator( )
int demon denominator op2.getDenominator( )
return new Rational(num, denom)
public Rational divide(Rational op2)
return multiply(op2.reciprical( ))
26
public Rational reciprocal( )
return new Rational(denominator, numerator)
public int getNumerator( )
return numerator public int
getDenominator( ) return
denominator public boolean
equals(Rational op2) return
(numerator op2.getNumerator()
denominator op2.getDenominator() )
public String toString( ) return
numerator "/" denominator
private void reduce( ) if (numerator
! 0) int common
gcd(Math.abs(numerator,
denominator)
numerator numerator / common
denominator denominator / common
private int gcd (int num1, int num2)
while (num1 ! num2) if (num1 gt
num2) num1 num1 num2 else
num2 num2 num1 return
num1
Write a Comment
User Comments (0)
About PowerShow.com