What are Classes, and How Do We Define Them - PowerPoint PPT Presentation

1 / 14
About This Presentation
Title:

What are Classes, and How Do We Define Them

Description:

TCSS142 Autumn 2004. What are Classes, and How Do We Define Them? ... every instance of PlayingCard has a rank and a suit ... the playing card's rank and suit ... – PowerPoint PPT presentation

Number of Views:27
Avg rating:3.0/5.0
Slides: 15
Provided by: Steve57
Category:
Tags: classes | define | suit

less

Transcript and Presenter's Notes

Title: What are Classes, and How Do We Define Them


1
What are Classes, and How Do We Define Them?
  • What classes have we seen so far?
  • What do they have in common?
  • How are they different?

2
Fundamental Principles of Classes
  • Classes have instances a class is a collection
    of instances
  • Each instance has its own state (instance
    variables)
  • every instance of Employee has an idNumber and a
    name
  • but the values of those variables will be
    different from instance to instance
  • every instance of PlayingCard has a rank and a
    suit
  • but the values of those variables will be
    different from instance to instance
  • Each instance responds to methods
  • every instance of Employee will probably respond
    to the getID() method
  • but the return result will be different
  • because the instance variables will have
    different value
  • every instance of PlayingCard will probably
    respond to the getSuit() method
  • So all instances of a class are alike in
    "appearance" but will have different behaviors
  • any instance of Scanner must respond to the
    nextLine() method, and must return an instance of
    String
  • but the actual String returned will be very
    different depending on what input stream the
    Scanner is hooked up to

3
Instance Variables Versus Methods
  • Instance variables store information about the
    object
  • the employee's ID number, name, and salary
  • the playing card's rank and suit
  • One of the main things a class does is control
    access to information in the instance variables
  • Examples
  • an Employee class has an firstName field, which
    applications can both "get" and "set"
  • an Employee class has an idNumber field, which
    can be read but not set
  • a PlayingCard class has a rank field, which is
    set when the object is created, and can be read
    but not set
  • an Employee class has a salary field which can be
    read, and can be set, but only to a positive
    number
  • a ComputerAccount class has a password field
    which can be set, and can be compared against a
    candidate password, but cannot be read directly
  • an ATM class has a cashOnHand field which is used
    for internal purposes only no method outside
    the class can read or write this value

4
The Three Components of a Class Definition
Instance variables what state do instances of
the class hold? private int idNumber
private String name private Employee
manager
public class Employee // Instance
variable(s) // Constructor(s) //
Method(s)
Constructors how do users of this class create
instances? public Employee(int id,
String name, Employee manager) public
Employee(int id, String name) public
Employee(String name) public Employee()
Methods what can an instance of this class be
asked to do? public int getID() public
String getName() public Employee
getManager() public void setManager(Employee
anEmployee) public String getDepartment()
public String getJobTitle() public void
assignTask(Task aTask)
5
Instance Variables
  • Instance variables are always private
  • Always
  • That means that all methods defined in the class
    definition can read and write them, but no
    methods outside the class definition can read or
    write them
  • Defining instance variables is done exactly the
    way you do it in any method data type, variable
    name, and optional initializer
  • it is unusual to initialize instance variables
    when they are defined
  • that's what the constructor is there for
  • Any method (including constructors) can access
    and change all the instance variables
  • the scope of an instance variable is the entire
    class
  • But no method outside of the class even knows the
    instance variable is there
  • because they are declared to be private

6
Constructors
  • A call to a constructor creates an instance of
    the class

Definition of constructor (in Employee.java) pub
lic class Employee public Employee(int id,
String name) . ..
Call to constructor (in EmployeeApplication.java)
Employee e new Employee(25, "Joe")
7
Constructors and Instance Variables
The Constructor's main job is to initialize
instance variables
public class Employee private int id
private String name private Employee
manager public Employee(int idIn, String
nameIn) id idIn name
nameIn ..
(But nothing forces it to do so in this
example, notice that the instance variable
manager is still uninitialized. That may well be
OK, if the "business rules" allow somebody not
to have a manager.)
8
The Default Constructor
  • Every class has a public 0-argument constructor
    built in. This creates an instance of the class
    with
  • all primitive values are initialized to 0 or
    false
  • all non-primitive values are initialized to null
  • Exercise write a simple class that verifies
    that this is true
  • what are the implications of initializing a
    variable of non-primitive type to null?
  • Sometimes this is extremely undesirable!
  • It means that any caller can create an instance
    of Employee with an ID number of 0 and a name of
    null
  • That will break almost any application program
  • To "disable" the default constructor, declare it
    to be private

public class Employee private Employee()

9
Methods
  • Recall the basic syntax for defining a method
  • this should look familiar except that we have
    been declaring our methods to be private (except
    main), and have been using the word static
  • We will begin by focusing exclusively on the
    public methods
  • these are the methods that can be used by any
    other class
  • private methods are internal helper methods (used
    within the class only) so they aren't interesting
    to us yet

public String getName( ) return name
10
Setter and Getter Methods
  • Two basic facts about classes
  • most users of the class are going to be
    interested in looking at or changing the class's
    state, i.e. the values of its instance variables
  • but the instance variables are always private, so
    no external class can do so!
  • A fundamental class design decision is how to
    permit access to the instance variables. Common
    usage patterns are
  • you can both access and change a variable (an
    Employee's name)
  • you can view but not access (an Employee's ID
    number)
  • you can change a value, but in a controlled way
  • an Employee's age
  • an Employee's wage rate
  • you cannot access or change a value (an account's
    password)

11
A Class's Public Interface
  • The set of public methods and public constructors
    make up the class's "public interface" or just
    "interface"
  • These are the ways the only ways that any
    other class or application can use the class
    being defined
  • You can use a class as a helper in getting your
    work done knowing only its public interface
  • you have been doing that with Scanner for the
    entire quarter!
  • When designing a class, you think first and
    foremost about what interface the class is going
    to implement (i.e. what its public methods are)
  • Example an Employee class with five pieces of
    information
  • name (fully settable)
  • salary (add or subtract, and can't be lt 10000)
  • id number (get but not set)
  • manager (settable, but can't be null after first
    set)
  • password (can only compare)

12
Methods and Class Invariants
  • There will almost always be constraints on what
    values instances of a class can take on
  • Example a checking account class with name,
    account number, PIN, and balance fields
  • name must be a non-empty string
  • account number must be an integer between 1000
    and 9999
  • PIN is a string at least 8 characters long with
    no whitespace
  • balance must be gt 0
  • These are called invariants, because they must be
    true of every instance of the class at all times
  • How do we enforce these rules?

13
Equality, Comparability, and Printing
  • Common things that an object must do
  • answer whether it is equal to another object
  • compare itself to another object
  • numbers gt numeric inequality
  • Strings gt lexicographic ordering
  • Scanners gt ??
  • Employees gt newer is less than older as measured
    by employee number? alphabetical order with
    respect to name?
  • produce a "nice" string representation of itself
  • generally one line, self-contained, for debugging
    purposes
  • print representation generally reveals the data
    type, and some unique identifier
  • Example an "ordered pair" class
  • (2,3) is something like x2, y3
  • (a, b) (c, d) iff (ac) AND (bd)
  • (a, b) lt (c, d) iff (a lt c) OR ((ac) AND (b lt
    d))

14
Static Variables and Methods
  • Every variable we have seen so far is an
    "instance variable" which means each different
    instance has distinct space allocated for the
    variable
  • every instance of Employee has a separate name
    variable
  • In some rare cases we want information to be
    shared among all instances of a class
  • the sum of all balances of all accounts
  • the next ID number that can be assigned a new
    employee
  • the total number of Employees currently active
  • And in some rare cases we want that information
    exposed to other classes
  • the total amount of money in the bank
  • the total number of Employees
  • Variables that are shared among all instances of
    the class are called static variables
  • Methods that are handled by the class, not an
    instance are called static methods
  • Two examples
  • bank accounts where total balance can be
    recovered
  • an Employee class where a unique ID number is
    assigned each time a new employee is constructed
Write a Comment
User Comments (0)
About PowerShow.com