next up previous contents
Next: Encapsulation Up: The Characteristics of an Previous: Abstraction   Contents

Sample Class Definition

Now let's create a real example: we will try to create the program for modelling a human being. The Human class will describe it as triggering between two common states: working, and resting. The class should inform its current state, fit for work or be sleeping or celebrating. As instance variables of the class we will use integer value tired and two strings, one will hold name and another one origin.

The corresponding line looks like this:

class Human {
  // code of the class
      ...
}

The key word in the definition is class, and its name is Human.

The behaviour of the new type is defined by three instance methods. One can be used to store a data in an object of the new type, it is named setPerson. The other one is named getHumanInfo can be used to retrieve a stored data from the object. The last one is named Work and implements the changing of the object tired, that is the member of a class Human. The code is not shown, we shall see it later.

The corresponding lines look like these:

// instance method to store data
    void setPerson (int state, String na, String orig) {
    ...
 }
// instance method to display info of a human
    String getHumanInfo() { 
   ...
 }
// instance method Work
    String Work() {
   ...
 }

This new type we can expand by incorporating other behaviours by means of setting up additional methods.

Having defined the new type, we may create instances of this type, i.e. objects, and deal with those objects similar we would deal with any other variables created from the primitive data types.


next up previous contents
Next: Encapsulation Up: The Characteristics of an Previous: Abstraction   Contents
Olexiy Ye. Tykhomyrov 2001-12-16