0% found this document useful (0 votes)
136 views

Java Chapter 8

Uploaded by

nicolle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
136 views

Java Chapter 8

Uploaded by

nicolle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

CHAPTER 8

OBJECTS AND
CLASSES

Slides by Donald W. Smith Final Draft


Copyright © 2013 by John Wiley & Sons. All rights reserved. TechNeTrain.com 10/30/2011
Chapter Goals
q  To understand the concepts of classes, objects
and encapsulation
q  To implement instance variables, methods and
constructors
q  To be able to design, implement, and test your
own classes
q  To understand the behavior of object references,
static variables and static methods
In this chapter, you will learn how to discover,
specify, and implement your own classes, and
how to use them in your programs.

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 2
Contents
q  Object-Oriented Programming
q  Implementing a Simple Class
q  Specifying the Public Interface of a Class

q  Designing the Data Representation


q  Implementing Instance Methods

q  Constructors
q  Testing a Class
q  Problem Solving:
§  Tracing Objects, Patterns for Object Data
q  Object References
q  Static Variables and Methods
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 3
8.1 Object-Oriented Programming
q  You have learned structured programming
§  Breaking tasks into subtasks
§  Writing re-usable methods to handle tasks
q  We will now study Objects and Classes
§  To build larger and more complex programs
§  To model objects we use in the world

A class describes objects with the same


behavior. For example, a Car class describes
all passenger vehicles that have a certain
capacity and shape.

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 4
Objects and Programs
q  Java programs are made of objects that interact
with each other
§  Each object is based on a class
§  A class describes a set of objects with the same
behavior
q  Each class defines a specific set of methods to
use with its objects
§  For example, the String class provides methods:
•  Examples: length() and charAt() methods
String  greeting  =  “Hello  World”;  
int  len  =  greeting.length();  
char  c1  =  greeting.charAt(0);  

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 5
Diagram of a Class
q  Private Data Class
§  Each object has its own private Private Data
data that other objects cannot (Variables)
directly access
§  Methods of the public interface
provide access to private data, Public Interface
while hiding implementation (Methods)
details:
§  This is called Encapsulation
q  Public Interface
§  Each object has a set of
methods available for other
objects to use

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 6
8.2 Implementing a Simple Class
q  Example: Tally Counter: A class that models
a mechanical device that is used to count people
§  For example, to find out how many people attend a
concert or board a bus
q  What should it do?
§  Increment the tally
§  Get the current total

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 7
Tally Counter Class
q  Specify instance variables in the class
declaration:

q  Each object instantiated from the class has its own
set of instance variables
§  Each tally counter has its own current count
q  Access Specifiers:
§  Classes (and interface methods) are public    
§  Instance variables are always private
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 8
Instantiating Objects
q  Objects are created based on classes
§  Use the new operator to construct objects
§  Give each object a unique name (like variables)
q  You have used the new operator before:
Scanner  in  =  new  Scanner(System.in);  
q  Creating two instances of Counter objects:
Class name Object name Class name
 
Counter  concertCounter    =  new  Counter();  
Counter  boardingCounter  =  new  Counter();  

Use the new operator to


construct objects of a class.

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 9
Tally Counter Methods
q  Design a method named count that adds 1 to the
instance variable public  class  Counter  
q  Which instance variable? {  
     private  int  value;  
§  Use the name of the object  
•  concertCounter.count()        public  void  count()  
•  boardingCounter.count()        {  
         value  =  value  +  1;  
     }  
 
     public  int  getValue()  
     {  
         return  value;  
     }  
}  

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 10
8.3 Public Interface of a Class
q  When you design a class, start by specifying the
public interface of the new class
§  Example: A Cash Register Class
•  What tasks will this class perform?
•  What methods will you need?
•  What parameters will the methods need to receive?
•  What will the methods return?
Task Method Returns
Add the price of an item addItem(double)   void

Get the total amount owed getTotal()   double

Get the count of items purchased getCount()   int

Clear the cash register for a new sale clear()   void

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 11
Writing the Public Interface
/**  
   A  simulated  cash  register  that  tracks  the  item  count  
   and  the  total  amount  due.  
*/   Javadoc style comments
public  class  CashRegister   document the class and the
{   behavior of each method
   /**  
       Adds  an  item  to  this  cash  register.  
       @param  price:  the  price  of  this  item  
   */  
   public  void  addItem(double  price)  
   {  
The method declarations make up
       //  Method  body  
   }   the public interface of the class
   /**  
       Gets  the  price  of  all  items  in  the  current  sale.  
       @return  the  total  price  
The data and method bodies make up
   */  
   public  double  getTotal()    ...  the private implementation of the class
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 12
Non-static Methods Means…
q  We have been writing class methods using the static
modifier: public  static  void  addItem(double  val)  
 
q  For non-static (instance) methods, you must instantiate
an object of the class before you can invoke methods

§  Then invoke methods of the object


public  void  addItem(double  val)  
 
public  static  void  main(String[]  args)  
{  
   //  Construct  a  CashRegister  object      
   CashRegister  register1  =  new  CashRegister();  
   //  Invoke  a  non-­‐static  method  of  the  object  
   register1.addItem(1.95);        
}  
 
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 13
Accessor and Mutator Methods
q  Many methods fall into two categories:  
1) Accessor Methods: 'get' methods
•  Asks the object for information without changing it
•  Normally return a value of some type
public  double  getTotal()  {    }  
public  int  getCount()  {    }  

2) Mutator Methods: 'set' methods


•  Changes values in the object
•  Usually take a parameter that will change an instance variable
•  Normally return void
public  void  addItem(double  price)  {    }  
public  void  clear()  {    }  

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 14
Special Topic 8.1: Javadoc
q  The Javadoc utility generates a set of HTML files
from the Javadoc style comments in your source
code
§  Methods document parameters and returns:
• @param  
• @return  

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 15
8.4 Designing the Data Representation
q  An object stores data in instance variables
§  Variables declared inside the class
§  All methods inside the class have access to them
•  Can change or access them
§  What data will our CashRegister methods need?
Task Method Data Needed
Add the price of an item addItem()   total,  count  

Get the total amount owed getTotal()   total  

Get the count of items purchased getCount()   count  

Clear the cash register for a new clear()   total,  count  


sale
An object holds instance variables
that are accessed by methods

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 16
Instance Variables of Objects
q  Each object of a class has a separate set of
instance variables.

The values stored in


instance variables make up
the state of the object.

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 17
Accessing Instance Variables
q  private instance variables cannot be accessed
from methods outside of the class
public  static  void  main(String[]  args)  
{  
   .  .  .  
   System.out.println(register1.itemCount);  //  Error  
   .  .  .   The compiler will not allow
}   this violation of privacy
q  Use accessor methods of the class instead!
public  static  void  main(String[]  args)  
{  
   .  .  .  
   System.out.println(  register1.getCount()  );  //  OK  
   .  .  .  
}   Encapsulation provides a public interface
and hides the implementation details.
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 18
8.5 Implementing Instance Methods
q  Implement instance methods that will use the
private instance variables
public  void  addItem(double  price)  
{  
   itemCount++;  
   totalPrice  =  totalPrice  +  price;  
}  

Task Method Returns


Add the price of an item addItem(double)   void

Get the total amount owed getTotal()   double

Get the count of items purchased getCount()   int

Clear the cash register for a new sale clear()   void

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 19
Syntax 8.2: Instance Methods
q  Use instance variables inside methods of the class
§  There is no need to specify the implicit parameter
(name of the object) when using instance variables
inside the class
§  Explicit parameters must be listed in the method
declaration

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 20
Implicit and Explicit Parameters
q  When an item is added, it affects the instance
variables of the object on which the method is
invoked

The object on which a


method is applied is the
implicit parameter

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 21
8.6 Constructors
q  A constructor is a method that initializes instance
variables of an object
§  It is automatically called when an object is created
§  It has exactly the same name as the class
public  class  CashRegister  
{  
   .  .  .  
   /**  
       Constructs  a  cash  register  with  cleared  item  count  and  total.  
   */  
   public  CashRegister()  //  A  constructor  
   {  
       itemCount  =  0;   Constructors never return values, but
       totalPrice  =  0;   do not use void in their declaration
   }  
}  

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 22
Multiple Constructors
q  A class can have more than one constructor
§  Each must have a unique set of parameters
public  class  BankAccount  
{   The compiler picks the constructor that
     .  .  .   matches the construction parameters.
     /**  
           Constructs  a  bank  account  with  a  zero  balance.  
     */  
     public  BankAccount(  )  {  .  .  .  }  
     /**  
           Constructs  a  bank  account  with  a  given  balance.  
           @param  initialBalance  the  initial  balance  
     */  
     public  BankAccount(double  initialBalance)  {  .  .  .  }  
}  
BankAccount  joesAccount  =  new  BankAccount();  
BankAccount  lisasAccount  =  new  BankAccount(499.95);  

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 23
Syntax 8.3: Constructors
q  One constructors is invoked when the object is created
with the new keyword

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 24
The Default Constructor
q  If you do not supply any constructors, the compiler
will make a default constructor automatically
§  It takes no parameters
§  It initializes all instance variables
public  class  CashRegister   By default, numbers are initialized to 0,
{  
booleans to false, and objects as null.
     .  .  .  
     /**  
           Does  exactly  what  a  compiler  generated  constructor  would  do.  
     */  
     public  CashRegister()  
     {  
           itemCount  =  0;  
           totalPrice  =  0;  
     }  
}  

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 25
CashRegister.java

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 26
Common Error 8.1
q  Not initializing object references in constructor
§  References are by default initialized to null  
§  Calling a method on a null reference results in a runtime
error: NullPointerException
§  The compiler catches uninitialized local variables for you  
public  class  BankAccount  
{  
   private  String  name;      //  default  constructor  will  set  to  null  
 
   public  void  showStrings()  
   {   Runtime Error:
       String  localName;   java.lang.NullPointerException
       System.out.println(name.length());  
       System.out.println(localName.length());  
   }  
Compiler Error: variable localName might
}   not have been initialized
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 27
Common Error 8.2
q  Trying to Call a Constructor
§  You cannot call a constructor like other methods
§  It is ‘invoked’ for you by the new reserved word
CashRegister  register1  =  new  CashRegister();  
§  You cannot invoke the constructor on an existing object:
register1.CashRegister();  //  Error  
§  But you can create a new object using your existing
reference
CashRegister  register1  =  new  CashRegister();  
Register1.newItem(1.95);  
CashRegister  register1  =  new  CashRegister();  
 
 

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 28
Common Error 8.3
q  Declaring a Constructor as void  
§  Constructors have no return type
§  This creates a method with a return type of void which
is NOT a constructor!
•  The Java compiler does not consider this an error
public  class  BankAccount  
{  
     /**  
           Intended  to  be  a  constructor.  
     */  
     public  void  BankAccount(  )     Not a constructor…. Just another
     {     method that returns nothing (void)
           .  .  .    
     }  
}  

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 29
Special Topic 8.2
q  Overloading
§  We have seen that multiple constructors can
have exactly the same name
•  They require different lists of parameters
§  Actually any method can be overloaded
•  Same method name with different parameters
void  print(CashRegister  register)      {  .  .  .  }  
void  print(BankAccount  account)          {  .  .  .  }  
void  print(int  value)            {  .  .  .  }  
Void  print(double  value)      {  .  .  .  }    
 
§  We   will not be using overloading in this book
•  Except as required for constructors

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 30
8.7 Testing a Class
q  We wrote a CashRegister  class but…
§  You cannot execute the class – it has no main method
q  It can become part of a larger program
§  Test it first though with unit testing
q  To test a new class, you can use:
§  Programming tools that interactively create objects:
•  DrJava: www.drjava.org
•  BlueJ: www.bluej.org
§  Or write a tester class:
•  With a main   public  class  CashRegisterTester    
{  
   public  static  void  main(String[]  args)  
   {  
       CashRegister  c1  =  new  CashRegister();  
       ...  
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 31
BlueJ: An IDE for Testing
q  BlueJ can interactively instantiate objects of a
class, and allows you to invoke their methods
§  Great for testing!

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 32
CashRegisterTester.java
q  Test all methods
§  Print expected
results
§  Output actual results
§  Compare results

A unit test verifies that a class


works correctly in isolation, outside
a complete program.

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 33
Steps to Implementing a Class
1) Get an informal list of responsibilities
for your objects

2) Specify the public interface

3) Document the public interface


§  Javadoc comments

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 34
Steps to Implementing a Class
4) Determine the instance variables

5) Implement constructors and methods

6) Test your class

Copyright © 2011 by John Wiley & Sons. All rights reserved. Page 35
8.8 Problem Solving: Tracing Objects
q  Use an Index card for each object

§  An object is manipulated through the public


interface (front of the card)
§  The encapsulated data is on the back of the
card

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 36
Mutator Methods and Cards
q  As mutator methods are called, keep track
of the value of instance variables
CashRegister  reg2(7.5);  //  7.5  percent  sales  tax  
reg2.addItem(3.95,  false);  //  Not  taxable  
reg2.addItem(19.95,  true);  //  Taxable  

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 37
8.9 Problem Solving
Patterns for Object Data
q  Common patterns when designing instance
variables
§  Keeping a Total
§  Counting Events
§  Collecting Values
§  Managing Object Properties
§  Modeling Objects with Distinct States
§  Describing the Position of an Object

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 38
Patterns: Keeping a Total
q  Examples public  class  CashRegister  
{  
§  Bank account balance
   private  double  totalPrice;  
§  Cash Register total  
§  Car gas tank fuel level    public  void  addItem(double  price)  
   {  
q  Variables needed        totalPrice  +=  price;  
   }  
§  Total (totalPrice)    public  void  clear()  
q  Methods Required    {  
       totalPrice  =  0;  
§  Add (addItem)    }  
§  Clear    public  double  getTotal()  
   {  
§  getTotal        return  totalPrice;  
   }  
}  
       
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 39
Patterns: Counting Events
public  class  CashRegister  
q  Examples {  
§  Cash Register items    private  double  totalPrice;  
   private  int  itemCount;  
§  Bank transaction fee    public  void  addItem(double  price)  
q  Variables needed    {  
       totalPrice  +=  price;  
§  Count        itemCount++;  
   }  
q  Methods Required    public  void  clear()  
§  Add    {  
       totalPrice  =  0;  
§  Clear        itemCount  =  0;  
§  Optional: getCount    }  
   public  double  getCount()  
   {  
       return  itemCount;  
   }  
}  
Copyright © 2013 by John Wiley & Sons. All rights reserved.
        Page 40
Patterns: Collecting Values
public  class  Cart  
q  Examples {  
§  Multiple choice    private  String[]  items;  
   private  int  itemCount;  
question    public  Cart()    //  Constructor  
§  Shopping cart    {  
       items  =  new  String[50];  
q  Storing values        itemCount  =  0;  
§  Array or ArrayList    }  
   public  void  addItem(String  name)  
q  Constructor    {  
       if(itemCount  <  50)  
§  Initialize to empty
       {  
collection            items[itemCount]  =  name;  
q  Methods Required            itemCount++;  
       }  
§  Add    }  
}  
       
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 41
Patterns: Managing Properties
public  class  Student  
A property of an object {  
can be set and    private  String  name;  
   private  int  ID;  
retrieved    public  Student(int  anID)  
   {  
q  Examples
         ID  =  anID;    
§  Student: name, ID    }  
   public  void  setName(String  newname)  
q  Constructor    {  
§  Set a unique value        if  (newName.length()  >  0)  
           name  =  newName;  
q  Methods Required    }  
   public  getName()  
§  set
   {  
§  get          return  name;  
   }  
}  
       
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 42
Patterns: Modeling Stateful Objects
public  class  Fish  
Some objects can be in one {  
of a set of distinct states.    private  int  hungry;  
   public  static  final  int  
q  Example: A fish NOT_HUNGRY  =  0;  
   public  static  final  int  
§  Hunger states: SOMEWHAT_HUNGRY  =  1;  
•  Somewhat Hungry    public  static  final  int  
•  Very Hungry VERY_HUNGRY  =  2;  
•  Not Hungry  
   public  void  eat()  
q  Methods will change the    {  
state          hungry  =  NOT_HUNGRY;  
   }  
§  eat    public  void  move()  
   {  
§  move    if  (hungry  <  VERY_HUNGRY)    
       {  hungry++;  }  
}  
Copyright © 2013 by John Wiley & Sons. All rights reserved.
  Page 43
       
Patterns: Object Position
q  Examples public  class  Bug  
{  
§  Game object    private  int  row;  
§  Bug (on a grid)    private  int  column;  
   private  int  direction;    
§  Cannonball //  0  =  N,  1  =  E,  2  =  S,  3  =  W    
q  Storing values    public  void  moveOneUnit()  
   {  
§  Row, column, direction,        switch(direction)  {  
speed. . .            case  0:  row-­‐-­‐;  break;  
           case  1:  column++;  break;  
q  Methods Required            .  .  .  
§  move        }          
   }  
§  turn }  
       

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 44
8.10 Object References
q  Objects are similar to arrays because they always
have reference variables
§  Array Reference

double[]  values  =  new  double[5];  


 
 

§  Object Reference

CashRegister  reg1  =  new  CashRegister;  


 
 
An object reference specifies the
memory location of the object

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 45
Shared References
q  Multiple object variables may contain references
to the same object.
§  Single Reference
CashRegister  reg1  =  new  CashRegister;  
 
 
§  Shared References
CashRegister  reg2  =  reg1;  
 
 

The internal values can be


changed through either reference

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 46
Primitive versus Reference Copy
q  Primitive variables can be copied, but work
differently than object references
§  Primitive Copy Reference Copy
•  Two locations One location for both
int  num1  =  0;   CashRegister  reg1  =  new  CashRegister;  
int  num2  =  num1;   CashRegister  reg2  =  reg1;  
num2++;   reg2.addItem(2.95);  
   
   

Why? Primitives take much less


storage space than objects!
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 47
The null reference
q  A reference may point to ‘no’ object
§  You cannot invoke methods of an object via a
null reference – causes a run-time error
CashRegister  reg  =  null;  
System.out.println(reg.getTotal());      //  Runtime  Error!  

§  To test if a reference is null before using it:


String  middleInitial  =  null;  //  No  middle  initial  
 
if  (middleInitial  ==  null)  
   System.out.println(firstName  +  "  "  +  lastName);  
else  
   System.out.println(firstName  +  "  "  +  middleInitial  +  ".  "  
+  lastName);  
 
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 48
The this reference
q  Methods receive the ‘implicit parameter’ in a
reference variable called ‘this’
§  It is a reference to the object the method was
invoked on:

§  It can clarify when instance variables are used:


void  addItem(double  price)  
{  
   this.itemCount++;  
   this.totalPrice  =  this.totalPrice  +  price;  
}  
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 49
Constructor this reference
q  Sometimes people use the this reference
in constructors
§  It makes it very clear that you are setting the
instance variable:
public  class  Student  
{  
   private  int  id;  
   private  String  name;  
   public  Student(int  id,  String  name)  
   {  
       this.id  =  id;  
       this.name  =  name;  
   }  
}  

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 50
8.11 Static Variables and Methods
q  Variables can be declared as static in the Class
declaration
§  There is one copy of a static variable that is shared
among all objects of the Class
public  class  BankAccount  
{  
   private  double  balance;  
   private  int  accountNumber;  
   private  static  int  lastAssignedNumber  =  1000;
 
 
   public  BankAccount()  
   {  
       lastAssignedNumber++;  
       accountNumber  =  lastAssignedNumber;  
   }  
   .  .  .   Methods of any object of the class can use
}   or change the value of a static variable
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 51
Using Static Variables  

q  Example:
§  Each time a new account is created,
the lastAssignedNumber variable is
incremented by the constructor
q  Access the static variable using:
§  ClassName.variableName  

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 52
Using Static Methods  

q  The Java API has many classes that provide


methods you can use without instantiating objects
§  The Math class is an example we have used
§  Math.sqrt(value) is a static method that returns the
square root of a value
§  You do not need to instantiate the Math class first
q  Access static methods using:
§  ClassName.methodName()  

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 53
Writing your own Static Methods
q  You can define your own static methods
public  class  Financial  
{  
     /**  
           Computes  a  percentage  of  an  amount.  
           @param  percentage  the  percentage  to  apply  
           @param  amount  the  amount  to  which  the  percentage  is  applied  
           @return  the  requested  percentage  of  the  amount  
     */  
     public  static  double  percentOf(double  percentage,  double  amount)  
     {  
           return  (percentage  /  100)  *  amount;  
     }  
static methods usually return a value. They
}  
can only access static variables and methods.
q  Invoke the method on the Class, not an object
double  tax  =  Financial.percentOf(taxRate,  total);  
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 54
Summary: Classes and Objects
q  A class describes a set of objects with the same
behavior.
§  Every class has a public interface: a collection of
methods through which the objects of the class
can be manipulated.
§  Encapsulation is the act of providing a public
interface and hiding the implementation details.
§  Encapsulation enables changes in the
implementation without affecting users of a class

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 55
Summary: Variables and Methods
q  An object’s instance variables store the data
required for executing its methods.
q  Each object of a class has its own set of instance
variables.
q  An instance method can access the instance
variables of the object on which it acts.
q  A private instance variable can only be accessed
by the methods of its own class.
q  Variables declared as static in a class have a
single copy of the variable shared among all of the
instances of the class.
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 56
Summary: Method Headers, Data
q  Method Headers
§  You can use method headers and method comments to
specify the public interface of a class.
§  A mutator method changes the object on which it operates.
§  An accessor method does not change the object on which
it operates.
q  Data Declaration
§  For each accessor method, an object must either store or
compute the result.
§  Commonly, there is more than one way of representing the
data of an object, and you must make a choice.
§  Be sure that your data representation supports method
calls in any order.
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 57
Summary: Parameters, Constructors
q  Methods Parameters
§  The object on which a method is applied is the implicit
parameter.
§  Explicit parameters of a method are listed in the method
declaration.
q  Constructors
§  A constructor initializes the object’s instance variables
§  A constructor is invoked when an object is created with
the new operator.
§  The name of a constructor is the same as the class
§  A class can have multiple constructors.
§  The compiler picks the constructor that matches the
construction arguments.
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 58

You might also like