Monday, November 1, 2010

More about Classes

First, a class is an abstract representation of an object. . .

A class can contain:
* fields
* properties
* methods
* constructors

Fields are class level variables. They describe a class. For instance, a Student class would have fields like studentID, name, email, major, gpa, etc. Fields should be kept private, which means nothing outside the class can see them or change them. This is part of encapsulation.

Properties are a special kind of method that are used to expose the private variables to other classes. Most properties contain two other methods: a Set which allows the user to change the value of the field, and a Get method that returns the value of the field. A property can just have a Get or just a Set. Additionally the programmer can add some validation to the property.

The idea of a property is to control access to the internal fields or variables. A property is marked by having no parenthesis at the end. (All other method and class initiations must have parenthesis.)

Methods are just as you have used them in the past. They do the work of the class. Each method must have a return type even if it is void. Methods can take parameters or not as needed. Any method with a return type other than void must have a return statement that returns a value of that type. Just like in the console apps we have done, each method should do one thing, though that thing could be complex. If you want other classes to be able to use the method you should declare it public.

Constructors, like properties, are also special methods. Constructors are used for initializing a class. In a constructor you can provide initial values for the field variables. You can also call any methods that need to run before the class is used. For example, you might call a method that connects to a database, so that when the class is used it is ready to read or write from the database. You can have more than one constructor. It is possible to overload constructors (or any other method) by creating a method with the same name but a different signature. The signature consists of the number and data types of the arguments.

Here are two constructors for the Student Class:


public Student()
{
StudentID=null;
StudentName=null;
GPA=0;
}

public student(string studID)
{
StudentID=studID;
StudentName=null;
GPA=0;

}



Constructors are marked by having the same name as the class and by having no return type.

If you don't create a constructor, .Net will create a default constructor for you that will initialize all your variables to 0 or null. If you create a constructor, any constructor, .Net will not create a default constructor and you will have to do all your own initializing.

No comments:

Post a Comment