Information Technology Reference
In-Depth Information
Accessing the Inherited Members
Inherited members are accessed just as if they had been declared in the derived class itself. For
example, the following code declares classes SomeClass and OtherClass , which were shown in
Figure 7-1. The code shows that all four members of OtherClass can be seamlessly accessed,
regardless of whether they are declared in the base class or the derived class.
￿ Main creates an object of derived class OtherClass .
The next two lines in Main call Method1 in the base class , using Field1 from the base class,
and then Field2 from the derived class.
￿
The subsequent two lines in Main call Method2 in the derived class , again using Field1
from the base class and then Field2 from the derived class.
￿
class SomeClass { // Base class
public string Field1 = "base class field";
public void Method1( string value ) {
Console.WriteLine("Base class -- Method1: {0}", value);
}
}
class OtherClass: SomeClass { // Derived class
public string Field2 = "derived class field";
public void Method2( string value ) {
Console.WriteLine("Derived class -- Method2: {0}", value);
}
}
class Program {
static void Main() {
OtherClass oc = new OtherClass();
oc.Method1( oc.Field1 ); // Base method with base field
oc.Method1( oc.Field2 ); // Base method with derived field
oc.Method2( oc.Field1 ); // Derived method with base field
oc.Method2( oc.Field2 ); // Derived method with derived field
}
}
This code produces the following output:
Base class -- Method1: base class field
Base class -- Method1: derived class field
Derived class -- Method2: base class field
Derived class -- Method2: derived class field
Search WWH ::




Custom Search