Information Technology Reference
In-Depth Information
For example, the following code shows the declaration and use of these two classes.
Figure 7-7 illustrates the object and references in memory.
Main creates an object of type MyDerivedClass and stores its reference in variable derived .
Main also creates a variable of type MyBaseClass and uses it to store a reference to the base class
portion of the object. When the Print method is called on each reference, the call invokes the
implementation of the method that that reference can see, producing different output strings.
class MyBaseClass {
public void Print() {
Console.WriteLine("This is the base class.");
}
}
class MyDerivedClass : MyBaseClass {
new public void Print() {
Console.WriteLine("This is the derived class.");
}
}
class Program {
static void Main() {
MyDerivedClass derived = new MyDerivedClass();
MyBaseClass mybc = (MyBaseClass)derived;
Cast to base class
derived.Print(); // Call Print from derived portion.
mybc.Print(); // Call Print from base portion.
}
}
This code produces the following output:
This is the derived class.
This is the base class.
Figure 7-7. A reference to the derived class and the base class
Search WWH ::




Custom Search