Title: Defining Your Own Classes
1Defining Your Own Classes
- Designing and defining a class.
- Variables attributes, parameters, and local
variables - Adding constructors and accessor/mutator methods
- James Brucker
2Designing a BankAccount Class
- What is the responsibility of this class?
- What functionality or behavior should it provide?
- What state do the objects need to carry out their
responsibilities? -
- Bank Account
- Every Bank Account must have a name (typically
the owner), a unique account number, and a
balance. It should provide methods to - deposit or withdraw money
- query the current balance
- query the account name
- print a neat one line summary of owner, account
number, balance
3Designing a BankAccount Class
- Every Bank Account must have a name (typically
the owner), a unique account number, and a
balance. It should provide methods to - deposit or withdraw money
- query the current balance
- query the account name
- print a neat one line summary of owner, account
number, balance
- Behavior
- credit( amount ) add money to the account
balance - debit( amount ) deduct money from the balance
- getName( ) return the account name (String)
- getBalance( ) return the current balance
(double)
4Designing a BankAccount Class
- Looking at the required behavior, what attributes
does a Bank Account object need? - balance the current balance. We'll use type
"double". - name a String containing the account name.
- accountID the account ID. String or int or
long? (Note Account numbers are always
10-digits.)
- Behavior
- credit( amount ) add money to the account
balance - debit( amount ) deduct money from the balance
- getName( ) return the account name (String)
- getBalance( ) return the current balance
(double)
5Diagram for a BankAccount Class
A UML class diagram
BankAccount name accountID balance getBalance(
) credit( double amount ) debit( double amount
) getName( )
The Class Name
The attributes
The interesting methods
6Limiting Accessibility
The attributes and methods of a class can be
designated as public - can be used from any
Java code. A public method can be called from
any code that references an object. A public
attribute can be assessed (or changed) from any
code than references an object. protected - can
only be used from inside the class or inside a
derived (child) class. private - can only be used
from inside the class.
- Guidelines
- Allow the outside program access only to the
methods/data it needs to perform its job. This
is the "public interface" to the class. - Methods that are part of the external interface
are public everything else is private or
protected. - Attributes (state) should be private or protected.
7Specifying Visibility/Assessibility
Indicate assessibility in UML class diagrams
using a prefix public protected -
private package
BankAccount - name - accountID - balance
getBalance( ) credit(double amount)
debit(double amount) getName( )
The Class Name
Private attributes
Public methods
8Declaring Attributes (1)
public class BankAccount private long
accountID private String name private double
balance
Attributes should normally be private or
protected.
- Attributes are properties of objects, not local
variables. - You should declare attributes near the top of the
class. - It is OK to declare attributes anywhere in the
class (except inside a method), but it makes them
hard to find.
9Declaring Attributes (2)
public class BankAccount / the account ID, a
10-digit number / private long
accountID / the account name / private
String name / the account balance, in Baht
/ private double balance
- Attributes are important! So, you should include
some comments describing them. - Javadoc comments of private members will be
included in web page if you use javadoc -private
10Initializing Attributes
public class BankAccount / the account ID, a
10-digit number / private long accountID
0 / the account name / private String name
"none" / the account balance, in Baht
/ private double balance 0
- There are 3 places where you can initialize
attributes - in a constructor (described later) necessary if
you want to initialize via parameters. - in an anonymous initialization block
- in the declaration statement
11Initialization of Attributes
- public class BankAccount
- private static double interestRate private
String accountNumber - private long balance
- private String accountName
- private int homeBranch
- / A lazy default constructor /
- public BankAccount( )
- balance 0
- / forgot to initialize other
- attributes.
- /
-
- If a class does not initialize all the attributes
then Java will set them to default values - zero for primitive types
- null for object references
Always Initialize Attributes! Don't depend on the
compiler to do it for you. In other languages it
is an error.
Implicit initialization accountNumber
null homeBranch 0 accountName null
12Four Types of Variables
Static Attributes belong to the class. There is
only one instance and its shared by all static
methods and objects.
- public class BankAccount
- private static long nextAccountNum
- private static double interestRate
- private String accountNumber
- private long balance
- private String accountName
- private int homeBranch
- / deposit money /
- public void deposit( int amount )
- String message ""
- if ( amount gt 0 )
- balance balance amount
- else message "Invalid ..."
- showError( message )
-
-
Instance Attributes belong to the objects. Each
object "owns" its own instances of these. The
values in one object have no effect on values in
other objects.
Parameters communicate information to a method.
A parameter exists only while the method is
executing.
Local variables used inside of a method. Local
variables exist only within the method and
aredestroyed when the method or ... block is
finished.
13Parameters send info to a method
BankAccount account new BankAccount( "Me"
) long n console.nextLong( ) account.
deposit( n )
send information to the method
public void deposit( long amount ) balance
balance amount
14Parameters pass by value
BankAccount account new BankAccount( "Me"
) long n 0 account. getBalance( n
) System.out.println( "Your balance is " n
)
This doesn't work! method cannot change the value
of a parameter.
public void getBalance( long amount ) amount
balance
15Initial Values
You must initialize local variables yourself. It
is an error to use the value of a variable before
it has been set to something.
public class BankAccount private long
accountID // default 0 private String name
// default null private long balance //
default 0 private static double interestRate
// 0 public void creditInterest( ) long
interest if ( balance gt 1000 ) interest
(long) balanceinterestRate balance balance
interest
Error! interest not initialized if balance lt
1000
16Initial Values (2)
The compiler doesn't analyze the logic of your
code. This example is an uninitialization error.
/ Assign a grade using the score. 90-100 is
A 80-90 is B ... _at_param score is the
student's total score / public String getGrade(
int score ) String grade null // a local
variable if ( score gt 90 ) grade "A" else
if ( score gt 80 ) grade "B" else if ( score
gt 70 ) grade "C" else /if ( score lt 70 )/
grade "F" return grade
Error! javac thinks that grade maybe
uninitialized.
17Accessor Methods
- A method that returns the value of an attribute
is called an accessor method. - The name of an accessor method is
usuallygetattributeName such
asgetBalance returns the value of
balancegetName returns the value of name - the code for these methods is very simple
private double balance // private
attribute ... / accessor method returns current
balance / public double getBalance( ) return
balance
18Benefits of Accessor Methods
- Outside code can read the value of an
attribute,but cannot change the attribute. - You can change the implementation of the
attribute without changing the outside code --
just don't change the assessor's signature.
Original Implementation
New Implementation
public class BankAccount private double
balance / accessor method / public double
getBalance( ) // balance, in Baht return
balance
public class BankAccount private long
balance//satang / accessor method / public
double getBalance( ) // balance, in
Baht return balance100.0
both return balance as a double.
19Information Hiding
- Using accessor and mutator methods you can
separate the external interface to a class from
the internal implementation of the class. - In object-oriented programming this is called
"information hiding" and is part of the concept
of "encapsulation".
20Mutator Methods
- A mutator method is one that enables the caller
to change the value of an attribute. - The name of a mutator method is, by
conventionsetattributeName such
assetName set the account name - A mutator should validate the argument before
changing an attribute.
private String name // private account name /
mutator method to modify acct name / public void
setName( String name ) if (name null)
ErrorMsg("Missing name") else if
(name.trim().length() lt 3 ) ErrorMsg("Name
must be at least 3 chars") else this.name
name
21Benefits of Mutator Methods
- Method can validate data before permitting a
change to the attribute avoids data
corruptions. - can also keep a record of changes (log file).
- You can change the implementation of an attribute
without changing code outside the class the
mutator method can adapt the old signature to new
attributes.
private String firstname, lastName public void
setName(String name) if ( name null ) /
error / String words name.trim().split("\
\s") if ( words.length ! 2 ) / error /
else firstName words0 lastName
words1
22Use of "this"
- Inside of instance methods Java defines a
variable named "this" to refer to this object. - Use can use "this" to...
- qualify the name of an attribute this.balance
- pass object to another method println( this )
public void deposit( long amount ) / you
can use "this" to specify attribute
/ this.balance this.balance amount
23Use of "this"
- If a parameter has the same name as an attribute,
the parameter name shadows (overrides) the
attribute inside of a method. - Use "this" when you want to refer to the
attribute.
public class BankAccount private long balance
0 // an attribute public void setBalance(
long balance ) / you must use "this" to
refer to the attribute balance.
/ this.balance balance
24Java Code for BankAccount (1)
/ Bank Account class _at_author James Brucker
ltjbrucker_at_yahoo.comgt / public class BankAccount
private long accountID private String
name private double balance / accessor
methods / public String getName( ) return
name public double getBalance( ) return
balance / credit funds to the account
balance. _at_param amount is the amount to
credit / public void credit( double amount )
balance amount
Attributes defined in class, not in methods.
25Java Code for BankAccount (2)
/ remove funds to the account balance.
_at_param amount is the amount to deduct
/ public void debit( double amount )
balance - amount / return a one line
summary of the account / public String
toString( ) return ""accountID" "name"
"balance // end of the class definition
Many classes define a toString( ) method. It is
implicitly called by Java if the object is used
in a print(...) or println(...) statement.
26More about toString( )
The toString() method is optional but very
desirable. A toString() method must have this
signature public String toString() / your
code goes here /
/ return a one line summary of the account.
_at_param none _at_returns String
representation of object. / public String
toString( ) return ""accountID" "name"
"balance
A useful String representation of the object.
- Return a String. Don't include trailing newline
('\n'). - Don't "print" anything ... that is the caller's
job.
27What's Missing?
- Is something missing from the class definition?
- How do you set the account name and ID?
- These values should be set when the account is
created. - To set attributes when an object is created, you
define a constructor. - A constructor is called when an object is
created, e.g. - BankAccount ku new BankAccount( )
- BankAccount ku new BankAccount( "KU",
1234567890 )
28Constructor
- A constructor is a method that is called when a
new object is created. - A constructor has the same name as the class.
- The constructor usually initializes the
attributes (state) of the object.
public class BankAccount private long
accountID private String name private double
balance / constructor / public BankAccount(
) accountID "unknown" balance 0
public double myMethod( ) BankAccount
acct ... acct new BankAccount( ) ... ...
29Constructor (2)
- A class can have several constructors. Java will
use the one that matches the arguments in the
"new" command. - If a matching constructor is not found, it is an
error!
public class BankAccount private long
accountID private String name private double
balance / constructor / public
BankAccount( String aName, long id ) name
aName accountID id balance 0
public double myMethod( ) BankAccount
acct ... acct new BankAccount( "T.
Shinawat", 12345678) ... ...
30Writing Constructors (1)
public class BankAccount private long
accountID private String name private double
balance / default constructor / public
BankAccount( ) accountID 0 name
"unknown" balance 0 / parameterized
constructor / public BankAccount(String aname,
long id) name aname accountID
id balance 0
The default constructor doesn't have any
parameters
No return value -- not even "void" !
31Writing Constructors (2)
public class BankAccount private long
accountID private String name private double
balance / default constructor / public
BankAccount( ) accountID 0 name
"unknown" balance 0 / a parameterized
constructor / public BankAccount(String aname,
long id) name aname accountID
id balance 0
Parameterized Constructors A class can have many
constructors, each with different parameters.
Initialize the attributes using parameter values
32Writing Constructors (3)
- A constructor can call another constructor using
this( ). - this() must be the first statement in the
constructor. - This is useful for eliminating duplicate code.
/ default constructor / public BankAccount(
) this("unknown, 0) / a
parameterized constructor / public
BankAccount(String aname, long id) name
aname accountID id balance 0
Constructor can call another constructor.
33Review Questions
- There is a new attribute named createDate date
the account was created. - Should this be static or instance attribute?
- What is the name of an accessor method for
createDate? What is the method signature? - Write the accessor method.
- What is the name of a mutator method for
createDate?
public class BankAccount private long
accountID private Date createDate private
double balance
34Exercise
- Create the BankAccount class, including
constructors. - Write a test program to test each method.
- Document the program. Create an HTML page.
35Do I Have to Write a Constructor?
- If your class does not have any constructors,
then Java will automatically supply a default
constructor ... that does nothing. - If your class has any constructors, Java does not
supply a default constructor. - When using inheritance (later), classes without
constructors can cause errors. - Reason when you create an object of a child
class Java also calls a constructor of the parent
class. If the parent class doesn't have the
required constructor it is an error.
36Common Errors
public class BankAccount private long
accountID // attributes private String
name private double balance / default
constructor / public void BankAccount( )
accountID 0 name "unknown" balance
0 / parameterized constructor / public
BankAccount(String aname, long id) String
name aname long accountID id double
balance 0
This is NOT a constructor.
This does NOT initialize the attributes.
37Constructors in Class Diagrams
You can include the constructor(s) in a class
diagram. Often, this information is not
interesting, so is not included.
BankAccount - name - accountID - balance
BankAccount( ) getBalance( ) credit()
debit() getName( )
Class Name
Attributes
Methods
38Parameters in Class Diagrams
You can include the parameter name and data type
in a class diagram.
BankAccount - name - accountID - balance
BankAccount( ) BankAccount( String name, long
id) getBalance( ) credit( double ) debit(
double ) getName( )
Class Name
Attributes
Methods
39Data types in Class Diagrams
You can include the data type of everything in
class diagrams. But, too much information makes
the diagram harder to read... and you have to
update it if you modify the class!
BankAccount - name String - accountID long -
balance double BankAccount( ) BankAccount(
String name, long id ) getBalance( ) double
credit( double amount ) void debit( double
amount ) void getName( ) String
Class Name
Format isname datatype
Attributes
Methods
40Summary (1)
- Classes can have both attributes and methods.
- The attributes contain the "state" of an object
they exist as long as the object exists. - The methods define the behavior of an object.
- A constructor is a method with the same name as
the class, that does not return a value... not
even "void". - Constructors are used to initialize an object's
attributes. - A constructor is called when an object is created
using the "new" command. - A class can have many constructors, each with
different parameters.
41Summary (2)
- You should limit the accessiblity of attributes
and methods. - Make "public" only methods that the application
needs to access the services of your class. - "final" constants that may be useful to the
application can be public. Example Math.PI
Color.RED