Upload
alice-heath
View
224
Download
1
Tags:
Embed Size (px)
Citation preview
CSSE501 Object-Oriented Development
Chapter 4: Classes and Methods
Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile time
representation of object-oriented programs. Chapter 5 discusses the dynamic, run time
behavior Both are important, and both chapters should be
understood before you begin further investigation of object-oriented programming
Same Ideas, Different Terms
All OOP languages have the following concepts, although the terms they use may differ: classes, object type, factory object instances, objects message passing, method lookup, member
function invocation, method binding methods, member function, method function inheritance, subclassing
Encapsulation and Instantiation What is a class?
A class is a category of objects; it is a new data type you create that is more complex than the basic data types
Classes provide a number of very important capabilities: Encapsulation - The purposeful hiding of information, thereby
reducing the amount of details that need to be remembered/communicated among programmers
A Service View - The ability to characterize an object by the service it provides, without knowing how it performs its task
Instantiation - The ability to create multiple instances of an abstraction
Examples
Student Book Vehicle Banking Account ……
Behavior and State
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)
Take the Student Class as an Example Student
Behavior Register/withdraw courses Provide or change his/her name, ID, average grade, Provide or change his/her contact information …
State Courses that are taking/taken Name, ID number, Average grade Address & Phone Number ….
Class Definitions
We will use the Student class as a running example for the class definition, and show how this appears in several languages
C++ Class Definition (Partial)
class Student {
int idNum;string name;double gradePointAverage;
void displayStudentData();};
Java Class Definition (Partial)class Student {
int idNum;string name;double gradePointAverage;
void displayStudentData();
}
Visibility Modifiers Accessibility to data fields (state) and
methods (behavior) Purpose
Information hiding Visibility of a class (interface, field, method) should
be as restricted as possible Clear abstraction of program components Does visibility of program components affect
security? Intuitively, it should
A secret may be embedded in an object as its private field
Untrusted code can be prevented from executing sensitive code by placing it in a package-local class
Visibility Modifiers The terms public and private are used to
differentiate the internal and external aspects of a class. Public
Public features can be seen and manipulated by anybody (All part of the application) -- they are the external (interface or service) view
Private Private features can be manipulated only within a
class. They are the internal (implementation) view Protected (Only in some, Not in all OO languages)
Protected features can be used only in the same package and from subclasses in other packages
Visibility Modifiers Typically in object-oriented technology
All the data fields should be private All the methods that are accessible by other
should be public Protected should only be used when a subclass
needs access to what would otherwise be a private member
C++ Class Definition (Partial)
class Student { private:
int idNum;string name;double gradePointAverage;
public:void displayStudentData();
};
Java Class Definition (Partial)class Student {
private int idNum;private string name;private double gradePointAverage;
public void displayStudentData();
}
Methods
Although syntax will differ depending upon language, all methods have the following: A name that will be matched to a message to
determine when the method should be executed A signature, which is the combination of return
type and argument types. Methods with the same name can be distinguished by different signatures
a body, which is the code that will be executed when the method is invoked in response to a message
C++ Class Definition (Partial)
//declaration section:class Student { private:
int idNum;string name;double gradePointAverage;
public:void displayStudentData();
};
//implementation section:void Student::displayStudentData(){ cout<<“Student #”<<idNum<< “’s name is “<<name<<endl;
cout<<“The grade point average for this student is “<<gradePointAverage<<endl;
}
Name: dispalyStudentData
Signature: void Student::displayStudentData()
Body
Java Class Definition (Partial)class Student {
private int idNum;private string name;private double gradePointAverage;
public void displayStudentData(){ system.out.println(“Student #” + idNum +” ‘s name is” + name); system.out.println(“The grade point average for this student is “ + gradePointAverage);}
}
Name: dispalyStudentData
Signature: public void Student::displayStudentData()
Body
Constructor A constructor
Is a method that is used to initialize a newly constructed object
Is called automatically each time an object is created
In C++, Java, C# and many other languages it has the same name as the class
A constructor cannot have a return type
C++ Class Definition (Partial)//declaration section:class Student { private:
int idNum;string name;double gradePointAverage;
public:Student();void displayStudentData();
};
Student::Student(){ idNum = 9999;
name = “J. Smith”;gradePointAverage = 0.0;
}
void Student::displayStudentData(){ ……}
A constructor without arguments
Java Class Definition (Partial)class Student {
private int idNum;private string name;private double gradePointAverage;
public Student(){ idNum = 9999;
name = “J. Smith”;gradePointAverage = 0.0;
}
public void displayStudentData(){ system.out.println(“Student #” + idNum +” ‘s name is” + name); system.out.println(“The grade point average for this student is “ +
gradePointAverage);}
}
A constructor without arguments
Accessor (or getter) Methods
Since all data fields should be private, how can we update or present a student’s information? Answer: through accessor or setter methods
An accessor (or getter) is a method that simply returns an internal data value Therefore, we can present private data fields
Why Use an Accessor? There are many reasons why an accessor is
preferable to providing direct access to a data field. You can make the data field read-only (private) It provides better documentation that the data field is
accessible It makes it easier to later change the access behavior
(count number of accesses, whatever)
Some conventions encourage the use of a name that begins with get, (as in getRank()), but this is not universally followed
C++ Class Definition (Partial)//declaration section:class Student { private:
int idNum;string name;double gradePointAverage;
public:Student();void displayStudentData();int getIDNum();string getName();double getGradePointAverage();
};
Student::Student(){ ……}
void Student::displayStudentData(){ ……}
Accessors
int Student::getIdNum(){ return idNum;}
string Student::getName(){ return name;}
double Sudent::getGradePointAverage(){ return gradePointAverage;}
Java Class Definition (Partial)class Student {
private int idNum;private string name;private double gradePointAverage;
public Student(){ …… }
public void displayStudentData(){ …. }
public int getIdNum(){ return idNum;}
public string getName(){ return name;}
public double getGradePointAverage(){ return gradePointAverage;}
}
Accessors
Setters (or mutators)
A setter (sometimes called a mutator method) is a method that is used to change the state of an object: Mutators are less common than
accessors, but reasons for using are similar
C++ Class Definition (Partial)//declaration section:class Student { private:
int idNum;string name;double gradePointAverage;
public:Student();void displayStudentData();int getIDNum();string getName();double getGradePointAverage();void setIDNum(int);void setName(string);void setGradePointAverage(double);
};
……
setters
void Student::setIdNum(int num){ const int MAX_NUM = 9999;
if (num <= MAX_NUM)idNum = num;
elseidNum = MAX_NUM;
}
void Student::setName(string nameIn){ name = nameIn;}
void Sudent::setGradePointAverage(double grade){ gradePointAverage = grade:}
Java Class Definition (Partial)class Student {
private int idNum;private string name;private double gradePointAverage;
public Student(){ …… }
public void displayStudentData(){ …. }
public int getIdNum(){ return idNum;}
public string getName(){ return name;}
public double getGradePointAverage(){ return gradePointAverage;}
}
public void setIdNum(int num){ const int MAX_NUM = 9999;
if (num <= MAX_NUM)idNum = num;
elseidNum = MAX_NUM;
}
public void setName(string nameIn){ name = nameIn;}
public void setGradePointAverage(double grade){ gradePointAverage = grade:}
setters
Constant Data Fields Some languages allow data fields to be declared as
constant (const modifier in C++, final in Java, other languages have other conventions).
Constant data fields can be declared as public, since they cannot be changed
class PlayingCard { // Java example
... public static final int Spade = 1; public static final int Diamond = 2; public static final int Club = 3; public static final int Heart = 4;
}
Order of Methods For the most part, languages don't care about the
order that methods are declared. Here are some guidelines: List important topics first. Constructors are generally very important, list them
first. Put public features before private ones. Break long lists into groups List items in alphabetical order to make it easier to
search. Remember that class definitions will often be read by
people other than the original programmer. Remember the readers, and make it easy for them
Internal and External Views
As we noted in the last chapter, encapsulation means there are two views of the same system. The outside, or service view, describes what an object does. The inside, or implementation view, describes how it does it
Separation of Definition and Implementation In some languages (such as C++ or Object Pascal) the
definition of a method can be separated from its implementation. They may even be in a different file
class PlayingCard {
public: ... Colors color () ; ... };
PlayingCard::Colors PlayingCard::color ( ) { // return the face color of a playing card
if ((suit == Diamond) || (suit == Heart)) return Red;
return Black; }
Considerations in Method Definitions
In C++ you have a choice to define a method in the class interface, or separately in an implementation file. How do you decide? Readability. Only put very small methods in the
class definition, so that it is easier to read. Semantics. Methods defined in class interface
may (at the discretion of the compiler) be expanded in-line. Another reason for only defining very small methods this way.
Interfaces in Java An interface is like a class, but it provides no
implementation. Later, another class can declare that it supports the interface, and it must then give an implementation. We will have much more to say about interfaces later after we discuss inheritance.
public interface Storing {
void writeOut (Stream s); void readFrom (Stream s);
};
public class BitImage implements Storing {
void writeOut (Stream s) { // ... } void readFrom (Stream s) { // ... }
};