Classes, Objects and Encapsulation.
Instructor Jeff Zhuk
| An Object is a self-contained set of data, and functions
that operate on that data.
Each object represents a function, feature,
or component of a larger system, much like a brick in a wall.
The object contains all of the data concerning its
function, along with a set of functions to access that data.
The data is generally private to the object, but may be declared
public if necessary.
The "outside world" access the data by using the object's function.
This is the concept of data encapsulation.
|
Classes define the data (attributes) and the operations
(methods) of the object.
Object are said to be of a particular class.
The class is like a blueprint, or plan for the object.
It defines the data, and functions to be included in the object.
The class command is used to declare the class.
A class is similar to a structure, but contains functions (methods) along with data.
|
Employee |
Attributes: name wage |
Operations: setName getName setWage getWage
|
|
If we want to declare a class that represents a person,
and their wages, we might use the following:
class CPPEmployee {
private: // data
char name[30];
int wage;
public: // methods
void setName(char* aName) {
strncpy(name, aName;
}
char* getName( ) {return name;}
void setWage(int salary) {
wage=salary;
}
int getWage( ) { return wage; }
}; // ! semicolon at the end of class
// Example of usage:
// Define two CPPEmployee objects
CPPEmployee first, secondEmployee;
//set name = "Peter" to the first
first->setName("Peter");
|
public class JavaEmployee {
// data
private String name;
private int wage;
// methods
public void setName(String aName) {
name = aName;
}
public String getName() {return name;}
public void setWage(int aWage) {
wage = aWage;
}
public int getWage() {return wage;}
} // There is no ";" at the end of class
// Example of usage:
// Define two JavaEmployee objects
JavaEmployee first, secondEmployee;
// set name = "Peter" to the first
first.setName("Peter");
|
Back to Object Oriented Concepts