CLASSES AND METHODS
IMPLEMENTING CLASS DIAGRAM IN
C++ AND JAVA
Classes encapsulation and Instantiation
2
Classes provide two very important capabilities:
Encapsulation - The purposeful hiding of
information, thereby reducing the amount of details
that need to be remembered/communicated among
programmers.
Instantiation - The ability to create multiple
instances of an abstraction.
Classes Behavior and State
3
A class can also be viewed as a combination of
behavior and state.
Behavior: The actions that an instance can perform in
response to a request. Implemented by methods.
State: The data that an object must maintain in order
to successfully complete its behavior. Stored in instance
variables (also known as data members, or data
fields).
State - Instance Variables
4
We have been using the term instance to mean a
representative or an example of a class.
We will use the term instance variable to represent the
state, or data values maintained internal to a class.
We can record information about the instance variable on
the back side of a CRC card, since it is internal to a class.
Clients can see the front of the card, implementers can
see the back of the card.
Example – Bank account
5
This is the front (public face) of a typical CRC
card.
Account
getBalance
getInterest
Deposit money
Withdraw money
Bank account - Data Areas
6
The back of the card can be used to record information
about the internal state of the card
Account - Implementation Information
double getBalance {The amount of money in the account};
double getInterest {The interest earned};
Deposit {Put some money into a bank account}
Withdraw {Remove some money from an account};
.
Revision of Account
7
We have refined the behavior by providing explicit
function names and argument types.
Account
double getBalance();
double getInterest();
deposit(double amount);
withdraw(double amount);
Varieties of Classes
8
There are four common forms of classes:
Data managers
Data sinks or sources
View or observer classes
Facilitator or helper classes
Varieties of Classes
9
Data Managers
Classes whose principal responsibility is to maintain
data values.
Account - maintains balance and account number
information.
Data Sinks and Sources
Objects that interface to data generators or
consumers, but do not hold data values themselves.
Input/Output Stream objects - files I/O devices
Varieties of Classes
10
View or Observer Classes
Classes that provide the graphical display of an object,
but are not the object themselves.
Tasks involved in viewing are different from tasks
involved in data manipulation
A single object might have many different forms of
views.
Facilitator and Helper Classes
Classes that maintain little or no state information, but
assist in the execution of complex tasks. An example
might be a painting assistant (Pen, Canvas, Edit box)
for a graphics output device.
Implementing Class State
Properties are sometimes called variables or states.
To declare a property use the following syntax:
["public" | "private" | "protected" ] [
"final/const" ][ "static" ] data_type
var_name
The access modifiers public, private and protected
determines the visibility or accessibility of the data
from other objects.
Implementing Class State
public means visible everywhere (global).
private indicates accessible only to this class and
nested classes.
protected means visible to this class or inherited (ie.
extended) classes only.
final in Java or const in C++ indicates continuous
retention and unchangeable after initial assignment
(i.e. it is a constant).
Implementing Class State
The data_type is one of the primitive types namely
int, float, double, char or reference type such as
String and can be optionally initialized
In C++, you do not have to provide access specifier
for each data, you use the specifier followed by a
list of the data members under that specifier:
class Employee {
private:
int idNum;
double salary;
: }
Implementing Class State
However in Java, you are required to state the
access level for each data member. For example:
public class Employee
{
private String name;
private int id;
private double gSalary;
:
}
Implementing Class Methods
Class behaviour are represented in Java by
methods also known as member functions in C++.
A method function provides an interface to the
private member data of the class.
Just like data members, you have to provide access
level to a method using syntax:
[ "public" | "private" | "protected" ] [ "final" ][
"static" | "abstract" | "native" ] return_data_type
method_name "(" parameter_list ")" "{" // some
defining actions "}"
Implementing Class Methods
static methods are shared by all members and exist
for all runtime. Static methods can be referenced
without creating an instance of the class.
abstract (Java) methods must be redefined on
inheritance.
native (Java) methods are written in C but
accessible from Java.
The return_data_type defines the type of value that
the calling routine receives from the object.
Implementing Class Methods
The parameter_list can contain from zero to many
entries of datatype varName pairs. Entries are
separated by commas.
In Java parameters are passed by value, thus
upholding the encapsulation principle by not
allowing unexpected changes or side effects.
Object references (such as arrays) can also be
passed.
Implementing Class Methods
Generally Java and C++ provides three types of
methods :
Constructor;
Accessor;
Mutator
Constructors
Construction of an object involves two actions:
Allocation of memory
Initialization of the object variables
Though constructors are optional their primary role of
a class constructor is to initialize each of the data
members of the class with values.
Constructors come into action when the object are
created.
Constructors
Public class Box
public Box()
{
length=0; width=0; height=0;
}
public Box(int l,int w,int h) {
length=l; width=w; height=h;
}
Constructors
Therefore a constructor:
Is a public member function
It is called when a new object is created (instantiated).
Initializes data members in a class.
Has same name as class
Does not have return type
One can use several constructors
Non-Parameterized constructor
Parameterize constructor
Overloaded constructor
Parameterized constructor
The constructors discussed earlier have no parameters.
For example the constructor employee has two default
arguments idNum= 120 and salary =100.0
Employee()
{
int idNum = 120;
double salary=100.0;
}
You can define a constructor that receives message from
an external and assigns the value to the member data
such as:
Parameterized constructor
class Sale {
private:
float taxRate;
float total;
Public:
Sale (float rate) {
taxRate =rate
} …};
The constructor purpose is to establish the tax rate
which may be used to compute the total sale
Overloaded constructor
Two or more constructors can share the same name as
long as their parameter list is different. The example
below demonstrates constructor overloading:
Public:
Sale ( ) {
taxRate = 0.16;
}
Sale (float rate) {
taxRate =rate
}
…};
Accessor Methods
Accessor (or observer) methods read property (ie.
field variable) values and returns the to the caller.
They are conventionally named getX() or whatever
the property is called.
For example:
public String getName()
{
return name;
}
Mutator methods
Mutator (or transformer) methods set property
values and are often named setFX() etc.
Mutators can be used modify state on behalf of the
caller method.
public void setName(String newName)
{
name = newName;
}
Once modification has been done, we can use getX
Mutator and Accessor methods
It is good programming practice to make each
property in a class private and include accessor and
mutator methods for them.
The exceptions to writing accessor/mutator methods
for each property is for those that are used only
within the class itself or for properties that are set in
more complex ways.
Other methods
Helper methods are those routines that are useful
within the class methods but not outside the class.
They can help in code modularization. Normally
they are assigned private access to restrict use.
Recursive methods are methods that are defined in
terms of themselves.
An example is factorials where n factorial is the
product of positive integer n and all the products
before it down to one.
Implementing Class in Java
public class Person
{
private String name;
public Person()//default constructor
{
name = "No name yet.";
}
public Person(String initialName)
{
name = initialName;
}
Implementing Class in Java
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
public void writeOutput() {
System.out.println("Name: " + name);
}
}
Creating and Clearing objects
Once an object has been created, it requires some
memory space.
To create an object of a particular class use the new
operator in Java. For Example:
Box new_box =new Box(3,4,5)
In C++ we can use the syntax:
ClassName ObjectName;
For Example
Employee workers[4];//4 employees
Creating and Clearing objects
Once the object is no longer useful, it has to be
cleared from memory.
In Java, you do not need to explicitly destroy or
remove an object when it is no longer needed.
Java automatically flags unused objects and
applies garbage collection when appropriate
In C++, to clear unwanted objects from memory we
define special type of method known as a
destructor
What is a destructor in C++?
It is a member function which deletes an object.
A destructor function is called automatically when the
object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing temporary variables ends
(4) a delete operator is called
A destructor has:
(i) the same name as the class but is preceded by a tilde (~)
(ii) no arguments and return no values
Constructors and destructors in C++
class base {
int a, b;
public:
base (int, int); //constructor interface
void display( ); //display method interface
~base ( ); //destructor
};
The class base has three methods one of which is a
constructor, a display and a destructor.
C++ Example 1
include<iostream>
using namespace std;
class Demo{
public:
Demo();
~Demo();
};
Demo::Dem()
{
cout<<"Welcome. This is OOP"<<endl;
}
Example 1
Demo::~Demo()
{
cout<<"Good bye\n";
}
int main(){
Demo Greetings;
cout<<"Demostrates a constructor and
displays goodbye when";
cout<<" a destructor is called\n";
return 0;
}
C++ Example 2
#include<iostream>
using namespace std;
class Employee {
private:
int idNum;
double salary;
public:
Employee()
{
int idNum = 120;
double salary=100.0;
Example 2
cout<<"Id number "<<idNum<<"\tSalary is
"<<salary<<endl;
cout<<endl;
}
~Employee ()//object is cleared from memory
{
cout<<"Object cleared from RAM\n";
}
};
void main(){
Employee workers;//constructor called
}
Interface and Implementation
In most OOP languages, the distinction between
interface and implementation is manifest on two
distinct levels:
Within a class, separation between interface and
implementation part
Interface descriptions and implementation bodies
appearing in separate files (or separate area of
same file).
For example, in C++, *.h files for interface and
implementation and *.cpp is the driver file.
Sale Class Interface file in C++
40
/* interface description for Sale class
saved with .h extension */
#ifndef SALE_H
#define SALE_H
//sale class interface definition
class Sale {
private:
float taxRate;
float total;
Sale Class Interface file in C++
41
//public methods prototypes
public:
Sale (float rate);
void calSales (float cost);
float getTotal ();
};
#endif
Implementation of Sale class
/* implementation of Sale class saved with .h
extension */
#include "sales_constructor_interface_only.h“
Sale::Sale (float rate) {
taxRate = rate;
}
void Sale::calSales (float cost){
total = cost + (cost*taxRate);
}
float Sale::getTotal () {
return total; }
Main program body
/* main allows the user to process sales
saved with .cpp extension */
#include<iostream>
#include<iomanip>
using namespace std;
#include "sales_implementation.h“
int main()
{
Sale cashier(0.16);//object cashier
float amount;
Main program body
cout<<fixed<<showpoint<<setprecision(2);
cout<<"Enter the amount of sale "<<endl;
cin>>amount;
cashier.calSales(amount);
cout<<"The total sale is
"<<cashier.getTotal()<<endl;
return 0;
}
Interface and implementation in Java
In Java interfaces are also used to separate design
from coding as class method headers are specified
but not their bodies.
This allows compilation and parameter consistency
testing prior to the coding phase.
We use the key words interface and implements.
When you create a class that uses an interface, you
reference the interface with the phrase implements
Interface_list
Interface and implementation in Java
public interface Job
{
public void work();//no implementation
}
public class WorkingClass implements Job
{
public void work(String job_title){
//some implementation code
}
}
What Next?
Inheritance and Polymorphism