Writing Classes
Prepared by Dr. Rania Minkara
COE 212 – Engineering Programming
Writing classes
• We have been using predefined classes, developed by SUN from the
Java standard class library.
✓Example of predefined classes:
• String class defined in [Link] package
• Scanner class defined in [Link] package
• Although existing class libraries provide many useful classes, the
essence of object oriented programming development is the process
of designing and implementing your own classes to suit your specific
needs.
2
Relationship between an object and a
class
• A class is the model, pattern, or blueprint from which an object is created.
• The blueprint of an object defines the important characteristics of the
object:
✓Blueprint of a house defines (walls, windows, doors, etc., …)
✓Once blueprint created ⇒ use it to build objects (houses)
• A class represents the concept of an object
✓Any object created is a realization of the concept
• Example: String class (concept) ⇒ String object (specific characters)
3
Example
• Suppose a class called student represents a particular student:
✓Student is the general concept of a student
• who has (name, address, Major, GPA)
• To whom you need (to set address, major, compute GPA)
• Every object created ⇒ an actual student
• In a system that helps manage the business of a university, you have
one student class and thousands of student objects.
4
Object
• An object has a state defined by the attributes associated with that
object:
✓Attributes of student → Student’s name, address, major, etc.,…
• It stores the values of attributes for a particular student whose
attributes are defined by variables declared within a class.
5
Object
• An object has behaviors defined by the operations associated with
that object:
✓Operations of a student → update student’s address, GPA, etc.,…
• It executes the operations defined by a class using the methods
declared within the class.
6
Examples of classes and possible attributes and operations
Class Attributes Operations
Length Set length
Rectangle Width Set width
Color Set color
Airline Set airline
Flight number Set flight number
Flight
Origin city Set origin city
Destination city Set destination city
Set name
Name
Set department
Employee Department
Compute bonus
Salary
Compute taxes
7
Classes
• A class can contain data declarations and method declarations
int size, weight;
Data declarations
char category;
Method declarations
8
Data Scope
• The scope of data is the area in a program in which that data can be
referenced (used).
• Data declared at the class level can be referenced by all methods in
that class.
• Data declared in a method can be used only in that method.
• Data declared within a method is called local data.
9
Encapsulation
• We can take one of two views of an object:
✓Internal
• The details of the variables and methods of the class that define it.
✓External
• The services that an object provides
• How the object interacts with the rest of the system.
• From the external view, an object is an encapsulated entity, providing
set of specific services
✓These services define the interface to the object.
10
Encapsulation
• An object should be self-governing:
✓Data of an object modified only by the object itself
✓We should make it difficult for code outside the class to change the value of a
variable declared inside class ⇒ encapsulation
11
Encapsulated object
• The code using the object is called client of the object:
• It should not be allowed to access variables directly
• It uses the methods instead to interact with data
Client Methods
Data
• Object encapsulation is achieved using visibility modifiers.
12
Visibility modifiers
• A visibility modifier is a Java reserved word that specifies the
characteristics of a method or data.
• It controls access to the members of a class.
• Java has two main visibility modifiers:
✓public: members of a class declared as public can be referenced anywhere.
✓private: members of a class declared as private can only be referenced
within the class.
13
Private variables
• Public variables violate encapsulation because they allow the client to
reach in and modify values directly:
✓Variables should not be declared with public visibility, they should be
declared as private.
• Methods that provide object’s services are declared with public
visibility so that they can be invoked by clients.
14
Accessors and mutators
• Data is generally private:
✓Class provides services to access data values through accessor methods
• Read only access to a particular value.
✓Class provides services to modify data values through mutator methods
• Change a particular value.
• These types of methods are sometimes referred to as “getters” and
“setters”:
✓The name of an accessor method takes the form getX where X is the name
of value.
✓The name of a mutator method takes the form setX.
15
Methods
• A method is a group of statements that:
✓Is given a name
✓Specifies the code executed, when the method is called
• One by one, the statements of that method are executed
• When done, control returns to the location of the call and execution continues
• The header of a method includes:
✓The type of the return value + method name + (list of parameters)
16
Method invocations
main helpMe
doThis
[Link]();
helpMe();
• If called method and calling method are in:
✓Same class → only method name is needed
✓Different class → invoke through the name of the other class
17
Method Header
• A method declaration begins with a method header:
char calc (int num1, int num2, String message)
method
parameter list
name
return
type
• The parameter list specifies the type and name of each parameter.
• The name of a parameter in the method declaration is called a
formal parameter.
18
Method Body
• The method header is followed by the method body:
char calc (int num1, int num2, String message)
{
int sum = num1 + num2; sum and result are local data
char result = [Link] (sum); created each time the method
is called, and are destroyed
return result; when it finishes executing
}
The return expression must be
consistent with the return type
19
Return type
• Return type specified in method header:
✓Primitive type or class name
• When the method returns a value
• In this case, the method must have a return statement
• Return statement: return + value to be returned
✓Or, the reserved word “void”
• When a method does not return any value
• In this case, the method does not contain a return statement and the control is returned
to the calling method at the end of the method.
20
The return Statement
• The return type of a method indicates the type of value that the
method sends back to the calling location.
• A method returning no value has a void return type.
• A return statement specifies the value that will be returned:
return expression;
• Its expression must conform to the return type.
21
Parameters
• The parameter list in the header of a method specifies:
✓The types of the values passed to the method
✓The names by which the method refer to those values
• The parameters are given in parentheses after the method name.
• If no parameters are required, an empty set of parentheses is used.
22
Local Data
• Local variables can be declared inside a method.
• The parameters of a method create automatic local variables when
method is invoked.
• When the method finishes, all local variables are destroyed.
• Instance variables declared at the class level exists as long as the
object exists.
23
Constructors
• When we define a class, we usually define a constructor:
✓A method that helps setting the class up
✓Often used to initialize variables associated with each object
• Constructors differ from regular methods:
✓The name of constructor is the same as the class
✓A constructor cannot return a value
• Does not have a return type
• A common mistake is to put a void return type on a constructor
24
Constructors
• Constructor is used to initialize the newly instantiated object.
• You don’t have to define a constructor for every class:
✓Each class has a default constructor taking no parameters
✓This default constructor is used if you don’t provide your own
✓Default constructor has no effect on the newly created object
25
Example
• Consider a six-sided die:
✓Its state can be defined as which face is showing.
✓Its primary behaviour is that it can be rolled.
• We can represent a die in software by designing a class called Die that
models this state and behaviour:
✓This class would serve as the blueprint for a die object.
• We can then instantiate as many die objects as we need for our
program.
26
Class design
• The Die class contains two data values:
✓A constant MAX that represents the maximum face value.
✓An integer faceValue that represents the current face value.
• Methods of the Die class:
✓Die: constructor; sets the initial face value of the die to 1.
✓Roll: roll the die by setting the face value to a random number between
one and six.
✓setFaceValue: sets the face value of the die to the specified value.
✓getFaceValue: returns the current face value of the die.
✓toString: returns a string representation of the die indicating its current
face value.
27
Instance Data
• The faceValue variable in the Die class is called instance data because
each instance (object) that is created has its own version of it.
• A class declares the type of the data, but it does not reserve any
memory space for it.
• Every time a Die object is created, a new faceValue variable is
created as well.
• The objects of a class share the methods but each object has its own
data space, that's the only way two objects can have different states.
28
Instance Data
• We can depict the two Die objects as follows:
die1 faceValue 5
die2 faceValue 2
• Each object maintains its own faceValue variable, and thus its own
state.
29
Constructor of Die class
public Die( )
{
faceValue = 1;
}
30
roll method
• The roll method uses the random method of the Math class to
determine a new face value.
public int roll( )
{
faceValue = (int)([Link]()*MAX)+1;
return faceValue; //return the new face value
}
31
Accessors and mutators of Die class
public int getFaceValue()
{
return faceValue;
}
public void setFaceValue(int value)
{
faceValue = value;
}
32
The toString method
public String toString()
{
String result = [Link](faceValue);
return result;
}
Note: the variable result is declared inside the toString
method, therefore, it is local to that method and cannot be
referenced anywhere else.
33
The toString method
• All classes that represent objects should define a toString method.
• The toString method returns a character string that represents
the object in some way.
• It is called automatically when an object is concatenated to a string or
when it is passed to the println method.
34
Die class
35
RollingDice class
Note: Any given program will not
necessarily use all aspects of a given
class.
36
37
Bank account example
• Let’s represent bank accounts by a class named Account
• State can include:
• Account number
• Current balance
• Name of the owner
• The account’s behaviors (or services) include:
• Deposits
• Withdrawals
• Adding interest
38
Driver Programs
• A driver program drives the use of other, more interesting parts of a
program.
• Driver programs are often used to test other parts of the software.
• The Transactions class (the driver program) contains a main method
✓Drives the use of the Account class exercising its services.
39
Constructor of Account class
public Account(String owner, long account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
}
40
deposit method
• Deposits the specified amount into the account and returns the new
balance.
public double deposit(double amount)
{
balance = balance + amount;
return balance;
}
41
withdraw method
• Withdraws the specified amount from the account, applies the fee and
returns the new balance.
public double withdraw(double amount, double fee)
{
balance = balance - amount - fee;
return balance;
}
42
addInterest method
• Adds interest to the account and returns the new balance.
public double addInterest( )
{
balance += (balance * RATE);
return balance;
}
43
getBalance method
• Returns the current balance of the account.
public double getBalance()
{
return balance;
}
44
toString method
• Returns a one-line description of the account as a string.
public String toString()
{
DecimalFormat fmt = new DecimalFormat("$#.00");
return (acctNumber + "\t" + name + "\t" + [Link](balance));
}
45
Account class
46
Transactions class
toString method is
automatically called
47
48
Bank Account Example
acct1 acctNumber 72354
balance 102.56
name “Ted Murphy”
acct2 acctNumber 69713
balance 40.00
name “Jane Smith”
49
Bank account example
• There are some improvements that can be made to the Account
class.
• Formal getters and setters could have been defined for all data.
• The design of some methods could also be more robust, such as
verifying that the amount parameter to the withdraw method is
positive.
50