Information Technology Reference
In-Depth Information
Example of an Abstract Class and an Abstract Method
The following code shows an abstract class called AbClass with two methods.
The first method is a normal method with an implementation that prints out the name of
the class. The second method is an abstract method that must be implemented in a derived
class. Class DerivedClass inherits from AbClass , and implements and overrides the abstract
method. Main creates an object of DerivedClass and calls its two methods.
Keyword
abstract class AbClass // Abstract class
{
public void IdentifyBase() // Normal method
{ Console.WriteLine("I am AbClass"); }
Keyword
abstract public void IdentifyDerived(); // Abstract method
}
class DerivedClass : AbClass // Derived class
{ Keyword
override public void IdentifyDerived() // Implementation of
{ Console.WriteLine("I am DerivedClass"); } // abstract method
}
class Example
{
static void Main()
{
// AbClass a = new AbClass(); // Error. Cannot instantiate
// a.IdentifyDerived(); // an abstract class.
DerivedClass b = new DerivedClass(); // Instantiate the derived class.
b.IdentifyBase(); // Call the inherited method.
b.IdentifyDerived(); // Call the "abstract" method.
}
}
This code produces the following output:
I am AbClass
I am DerivedClass
Search WWH ::




Custom Search