but this is not the case. Instead,
house1
object. The
does. Thus, the object can be acted upon by either
. For example, after the
116
P a r t I :
T h e C # L a n g u a g e
executes, both of these
WriteLine( )
statements
Console.WriteLine(house1.Area);
Console.WriteLine(house2.Area);
display the same value: 2600.
Although
house1
and
house2
both refer to the same object, they are not linked in any
other way. For example, a subsequent assignment to
house2
simply changes what object
house2
refers to. For example:
Building house1 = new Building();
Building house2 = house1;
Building house3 = new Building();
house2 = house3; // now house2 and house3 refer to the same object.
After this sequence executes,
house2
refers to the same object as
house3
. The object referred
to by
house1
is unchanged.
Methods
As explained, instance variables and methods are two of the primary constituents of classes.
So far, the
Building
class contains data, but no methods. Although data-only classes are
perfectly valid, most classes will have methods.
Methods
are subroutines that manipulate
the data defined by the class and, in many cases, provide access to that data. Typically, other
parts of your program will interact with a class through its methods.
A method contains one or more statements. In well-written C# code, each method
performs only one task. Each method has a name, and it is this name that is used to call
the method. In general, you can name a method using any valid identifier that you please.
However, remember that
Main( )
is reserved for the method that begins execution of your
program. Also, don’t use C#’s keywords for method names.
When denoting methods in text, this book has used and will continue to use a
convention that has become common when writing about C#. A method will have
parentheses after its name. For example, if a method’s name is
GetVal
, then it will be
written
GetVal( )
when its name is used in a sentence. This notation will help you
distinguish variable names from method names in this book.
The general form of a method is shown here:
access ret-type name
(
parameter
-
list
) {
// body of method
}
Here,
access
is an access modifier that governs what other parts of your program can call the
method. As explained earlier, the access modifier is optional. If not present, then the method
is private to the class in which it is declared. For now, we will declare methods as
public
so
that they can be called by any other code in the program. The
ret
-
type
specifies the type of
data returned by the method. This can be any valid type, including class types that you
create. If the method does not return a value, its return type must be
void
. The name of the
method is specified by
name.
This can be any legal identifier other than those that would
cause conflicts within the current declaration space. The
parameter-list
is a sequence of type
www.freepdf-books.com