Class. Class definition. Object of class. Constructor of the class. Destructor. Keyword this

Classes. Part 1

Class. Class definition. Object of class. Constructor of the class. Destructor. Keyword this


Content


1. What is the class and object of the class?

A class is a template that determines the shape of the object. Classes are like types in a traditional programming language. The difference is that users can define new types in an object-oriented programming language.

If a class is like a type in a traditional programming language, then an object is like a variable. Sometimes objects are referred to as instance of a class.

Object class implements one of the possible variants of the class definition. When is defining an object of class the memory is allocated.


2. What difference between class definition and object of the class?

When class is defined, the memory is not allocated. Is formed only description of the class members. Class definition is called the class declaration. In the description of the class are specified data and program code.

As a rule, the program code executes the some work under the data in the class (operates data in the class). When class is defined, the memory for data and program code is not allocated. The class definition – this is an information about, what data are in this class, and what work is executed to these data.

If the object of a class is defined, then, based on the class definition, the memory is allocated for this object. Thus class is a physical abstraction. Physically, the class will be represented only after the description of the object of class.


3. What is declared in the class?

When class is defined then data of this class are declared. Also is declared a program code which operates these data.

Also, a class can define only data or only the program code. But when you are working with the classes then the most classes define the data and a program code.

02_02_02_07_01eData are encapsulated in the data members, which are defined in the class, but a code – in the member-functions. In C # are supported several types of data members and member functions.


4. What is called the fields of a class?

The data members are called the fields of class. The variables of the class instance and static variables are the data members. Class fields can be any valid type in the application.


5. What are the C # language elements can be referred to member functions of a class?

To the member functions of a class can be referred:

  • methods;
  • constructors;
  • destructors;
  • indexers;
  • events;
  • operators;
  • properties.


6. What is the general form of class definition?

Class is created by using a keyword class. The general form of a class definition is following:

class class_name
{
   // Declaring of variables of class instance.
   access type variable1;
   access type variable2;
   // ...
   access type variableN;

   // Declaring of methods.
   access returning_type method1(parameters)
   {
      // body of the method
   }

   access returning_type method2(parameters)
   {
       // body of the method
   }

   // ...
   access returning_type methodN(parameters)
   {
       // body of the method
   }
}

In the above description:

class_name – the name of a class. The class name defines a new data type. Name of the class can respond the entity of class. In turn, the class must define one (and only one) logical entity;

access – this is an access type. The C# language provides four access modifiers: public (public class member); private (private member of the class); protected (protected class member) and internal. The internal modifier defines the accessibility of class member in the all members of the assembly and its availability outside the assembly.

type – the type of variable that is a class member;

variable1, variable2, …, variableN – variables that are class members (data in the class);

method1, method2, …, methodN – methods (functions) that are class members;

returning_type – type that is returned by the class method;

parameters – the parameters of methods that are defined in the class.


7. What are the types (modifiers) of access to the class members?

 The access to the class members can be one of four types:

private – private access. In this case members (data or methods) of a class are accessible only into the class boundaries. This means that access to private members of the class, have only variables and methods in this class;

public – public access. In this case, the class members are accessible outside the class. It means that public class members can be used in other code snippets even outside the class;

protected – the protected access. The given type is used in the case of inheritance when class hierarchy is built. Such members of a class are open in the boundaries of the class hierarchy, but they are closed outside the class hierarchy;

internal – it determines the availability of a member of the class in all the assembly files and it inaccessibility outside the assembly. This means that the internal-class members are known only in the program, but not outside the program. This modifier is useful when you need to create the program components.


8. What access gives the modifier “protected internal“?

The paired access identifier “protected internal” consists of two separate modifiers “protected” and “internal“.

This access level may be used only for the class members. The class member, that is declared as “protected internal“, is accessible only in the boundaries of it’s own assembly (internal) or it is accessible for the derived classes or types (protected).


 9. Can be missed the access type modifier when members of a class are declared?

Answer: yes, it can be missed. In this case, the declared class member is private by default.

Example.

...

// declaration of class of MyPoint type
class MyPoint
{
    int x; // x - private member
    public int y;
}

...

// access to the class member
MyPoint p = new MyPoint();

// p.x = 25; - error!, access is closed
p.y = 13; // it works, because p.y declared as public

...


10. Examples of simple classes declarations, that include data only.

Example 1. Class that includes only data. In this example, the new type MyPoint is created. The public class MyPoint is declared. This class defines a point on the coordinate plane.

...

public class MyPoint
{
    public int x; // coordinate x
    public int y; // coordinate y
}

...

Example 2. Definition of class MyBook, that describes data about a book.

...

public class MyBook
{
    public string Title; // the title of a book
    public string Author; // author name
    public int year;     // year of issue
    public float price;   // book cost
}

...


11. How create the object (class instance)?

After class declaration the new type is created. In the previous paragraph the MyPoint type is created. The class object is defined as a regular variable of the some type.

Example 1. Creating the object of MyPoint type (see previously paragraph).

Way 1. Creating of the object of MyPoint type with name p.

MyPoint p = new MyPoint(); // is created variable p of MyPoint type
// is allocated the memory for class object MyPoint
// to the variable p is assigned the reference to the object

// filling the fields of the class
p.x = 25;
p.y = -10;

Way 2.

MyPoint p;

p = new MyPoint(); // memory allocation - is required!!!, else - error

// filling the fields of the class
p.x = 25;
p.y = -10;

Example 2. Creating the class instance of MyBook type (see the previous paragraph) with name b.

MyBook b = new MyBook();

// filling the fields of the class
b.Title = "Title of Book";
b.Author = "Author of Book";
b.year = 1998;
b.price = 0.01f;


12. To which data types belong classes: to the type of value or reference types?

 Classes belong to the reference types. The difference between reference types and value types is that the variable of value type contains a value. And variable of reference type contains the reference to the object (but doesn’t this object).

Example.

// variable z is the double type, which is the value-type
double z;
z = 2.85; // in the variable z is saved the value 2.85

MyPoint p; // is created the variable p of type MyPoint
p = new MyPoint(); // the memory is allocated using the "new" operator
// for the variable p is assigned the reference on the allocated memory

In the given example, the address of created class instance in the memory is put to the variable p. The next figure shows the schematic difference between reference types and value types.

02_02_02_07_02_


13. Example of class definition, which contains data and methods (functions).

You can do some work above data in the class. It is realized by using a member functions.

In the next code snippets are described the classes with their own functions.

Example 1. Modification of MyPoint class, that includes of points coordinates. Four new member functions are added to the class:

– function GetX(), that returns a x coordinate;

– function GetY(), that returns a y coordinate;

– function SetX(), which sets the x coordinate to the new value;

– function SetY(), which sets the y coordinate to the new value.

The internal variables x and y of the class are declared as private.

class MyPoint
{
    // internal variables - are declared as private
    private int x;
    private int y;

    // member function of class – GetX()
    public int GetX()
    {
        return x;
    }

    // member function of class – GetY()
    public int GetY()
    {
        return y;
    }

    // member function of class SetX()
    public void SetX(int newx)
    {
        x = newx;
    }

    // member function of class – SetY()
    public void SetY(int newy)
    {
        y = newy;
    }
}

...

// using the class in the program
MyPoint p = new MyPoint();

// calling the functions - class members
p.SetX(5);
p.SetY(8);

// p.x and p.y - are unaccessible

// displaying the x-coordinate of class object p on the form
label1.Text = p.GetX().ToString();

...


14. What is the constructor? What are the differences between class methods and constructors?

 Syntactically, a method is similar to the constructor. The constructor initializes the class object, when it is created. The name of the constructor is the same as a class name. Constructor cannot return a type, which is specified explicitly.

As a rule, the constructor is applied for:

– setting of the initial values in the variables of class instance;

– performing some initial operations that are needed to creating the fully formed object.


15. What the general form of a constructor?

The general form of constructor is as follows:

access class_name(parameters)
{
    // constructor body
}

where

access – access modifier. In the most cases it is the “public” modifier. If the constructor is called outside the boundaries of a class, then it must be as “public“.

parametersthe list of parameters, which constructor takes. Parameters list can be empty.

An example of declaration the constructor of class MyPoint (see previous paragraphs). In the given constructor two parameters are taken. The names of these parameters: newx and newy. These parameters initializes the internal variables x and y of the class.

...

public MyPoint(int newx, int newy)
{
    x = newx;
    y = newy;
}

...

// using of the declared constructor, when class instance is created
MyPoint p = new MyPoint(5,8);


16. How many constructors can be specified in the class?

Any class can contain any number of constructors, which must differ one from another by the number of parameters and/or by the types of parameters.


17. What means the constructor by default?

If you did not declare constructor in a class, the C# language automatically will create the constructor by default. This constructor initializes all variables of class instance by their values by default.

For most data types, the default value is zero, for type boolfalse, for the reference type – empty value.

Example. Let there be given class MyBook, that contains data only. In the class are not declared constructors. Anyway, when you create an instance of the class (operator new), the default constructor is called.

...

class MyBook
{
    private string Title;
    private string Author;
    private int year;
    private float price;
}

...

// using of class in the program
// the constructor by default MyBook() is called, which doesn't declared explicitly
MyBook mb1 = new MyBook();

...


18. Example of initializing of the class using a constructors.

Let there be given a definition of class MyBook. In the class MyBook are described two constructors. One of them is the constructor without parameters. Second constructor takes four parameters, which fill the corresponding internal fields of MyBook class.

...

class MyBook
{
    // class fields - are declared as "private"
    private string Title;
    private string Author;
    private int year;
    private float price;

    // constructor without parameters
    public MyBook()
    {
        Title = "";
        Author = "";
        year = 1900;
        price = 0.00f;
    }

    // constructor with four parameters
    public MyBook(string t, string a, int y, float p)
    {
        Title = t;
        Author = a;
        year = y;
        price = p;
    }
}

...

// using of the constructors when class data (fields) are initialized
MyBook mb1 = new MyBook();
MyBook mb2 = new MyBook("Title-1", "Author-1", 2000, 3.99f);


19. What is the “garbage collection” in C#?

When program is running, when class objects are created, there is an allocation of memory by the new operator. After when the object did the work, it (may be) isn’t used in the program (but memory is allocated for it). If a program created many classes of objects, a situation may arise when the allocated memory is not enough to create the next object.

In this case, is important free the allocated memory, that were allocated for the objects, which are not used already. For this the system of dynamical memory allocation C# uses so-called “garbage collection”. If there is a “garbage collection” then frees the memory for objects that are not used.


20. How the system of “garbage collection” defines: is used the object or not?

 To define, is used object or not, the system of “garbage collection” scans the references to this object. If the references are not available, then this object is not used and it is needed free the memory for it. In the following this frees memory can be used for reallocation of others objects. Further this freed memory can be used for the distribution of other objects.


21. How often occurs the “garbage collection” in the system of dynamic control of memory C#?

If the object that is used becomes unnecessary, the memory that allocated to it, cannot be free immediately, but it can be free later. In the system of dynamical memory control C#, “Garbage collection” occurs only from time to time when program is running. The “garbage collection” cannot occurs, if there are few objects that are not used.


22. What is the purpose of using destructors?

There are cases in the program, when it is needed execute the actions before the freeing of the memory, that were allocated to the object. Destructor is the method which is called for guarantee freeing memory for the object.

In the destructor are pointed the actions, which is needed to do before the object will deleted.

The general form of destructor is following:

class_name()
{
   // the code of destructor
}

where class_name – name of the class.

Destructor has no returned type and has no parameters list.


23. Example of using the internal classes and definition of the destructor.

In the example below, are created two classes. First from their is of MyBook type. Second – array of books MyBooks. In class MyBooks is declared the destructor.

class MyBook
{
    // class fields - are declared as private
    private string Title;
    private string Author;
    private int year;
    private float price;

    // the class constructor without parameters
    public MyBook()
    {
        Title = "";
        Author = "";
        year = 1900;
        price = 0.00f;
    }

    // the class constructor with fours parameters
    public MyBook(string t, string a, int y, float p)
    {
        Title = t;
        Author = a;
        year = y;
        price = p;
    }
}

// class - array of books
class MyBooks
{
    MyBook[] mas_books; // array of books

    // the constructor of class MyBooks
    public MyBooks()
    {
        // memory allocation under the array
        mas_books = new MyBook[10];

        // memory allocation for separate item of array
        for (int i = 0; i < 10; i++)
        {
            // calling of the constructor with four parameters
            mas_books[i] = new MyBook("T" + i.ToString(),"A" + i.ToString(),i, (float)(i * 5));
        }
    }

    // destructor of class MyBooks
    ~MyBooks()
    {
        // actions that needs to be done before the destruction of the object
        // ...
    }

    // The internal method, that returns a book that given by the index.
    public MyBook GetBook(int index)
    {
        return (MyBook)mas_books[index];
    }
}

...

// using in the program
MyBooks MB = new MyBooks(); // in the constructor is created the array from 10 books of type MyBook

...


24. What features of use the keyword “this” in the class?

When the class object is defined, the all members of this object get implicitly the reference “this“, which is the reference to this object.

Example. Declaration of the class DemoThis. There are two fields in the class. One of them is as private and is type “int” and is named “i“. The second field is public, it is of “double” type and named “d“. Two methods GetI1() and GetI2() are declared in the class. These methods return the value of field “i“. These methods do the same work, but access to the field “i” is realized differently. The same applies to GetD1() and GetD2(). In the class constructor DemoThis(int, double), that takes two parameters, the keyword “this” ised for access to the fields i and d of class. This is due to the fact that the local parameters, that are variables of the constructor with the same names (i and d), hide the data members of declared class.

class DemoThis
{
    private int i;   // private field
    public double d; // public field

    // the constructor, which zeroes the fields
    public DemoThis()
    {
        i = 0; // without the word "this"
        this.d = 0.00; // by using "this"
    }

    // The given constructor demonstrates the benefit of using keyword "this".
    // The constructor takes two parameters, names of them are the same
    // as names of fields of class
    public DemoThis(int i, double d)
    {
        this.i = i; // this.i - class field: private int i;
        this.d = d; // this.d - class field: public double d;
    }

    // returning from the method without using "this"
    public int GetI1()
    {
        return i;
    }

    // using the reference "this" at the own class
    public int GetI2()
    {
        return this.i;
    }

    public double GetD1()
    {
        return d; // without reference "this"
    }

    public double GetD2()
    {
        return this.d; // using the reference "this"
    }
}