Fall 2020
September 24, 2020
ComputePerimeter or MultiplyRectangle methods.| ClassRoom |
|---|
- name: string |
- number: int |
+ SetName(nameParameter : string): void |
+ GetName(): string |
+ SetNumber(numberParameter: int): void |
+ GetNumber(): int |
What if we display the values of the instance variables before setting them?
ClassRoom english = new ClassRoom();
Console.WriteLine(english.GetName()); // Nothing!
Console.WriteLine(english.GetNumber()); // 0Indeed, instance variables are different from “usual” variables in that sense that they receive a “default” value when created. This value depends of the variable datatype:
| Type | Default |
|---|---|
| numerical value | 0 |
| char | '\x0000' |
| bool | false |
| string | null |
A constructor is a method used to create an object. It has to have the same name as the class, and doesn’t have a return type.
public ClassRoom(string nameParameter, int numberParameter)
{
name = nameParameter;
number = numberParameter;
}We use it as follows:
Note:
void)In the UML diagram, we would add:
+ <<constructor>> ClassRoom(nameParameter: string, numberParameter: int)
Note that we could skip the <<constructor>> part, can you tell why?
If we implement this constructor, then we lose the “No args”, default constructor
We can re-define it, using something like:
Every method has a signature made of - its name, - its parameters types (but not the parameter names).
Note that the return type is not part of the method signature in C#.
In a class, all the methods need to have a different signature. You cannot, for example, have these two methods in the same class:
It is possible, however, to have two methods with the same name, as long as they have different signatures. If we are in such a situation, then we say that we are overloading. We will look at examples of overloading in lab.
A particular method can be used to display information about our objects. It is called ToString, and can be defined as follows:
We will look at examples and usage in class and lab.