Anda di halaman 1dari 2

The abstract modifier is used in classes, methods and properties.

Abstract modifier is used when you want the class to be a base class for other classes.
Key points concerning abstract classes:

• May not be instantiated.


• May contain abstract methods and accessors.
• Cannot be modified with the sealed modifier.
• A non-abstract class derived from an abstract class must include actual
implementations of all the inherited abstract methods and accessors

You may use the abstract modifier in methods and properties to serve the same purpose
of not having implementations of it.
Key points concerning Abstract methods:

• It is implicitly a virtual method.


• May only be declared in abstract classes.
• There is no method body since there is no implementation of it during declaration.
E.g.
public abstract void GetUserInfo(); // no {} after the signature

• The actual implementation is provided by an overriding method which is of
course of a non-abstract class.
• The following modifiers are not allowed in an abstract method declaration: static,
virtual and override.

Abstract properties are similar to abstract methods except for declaration and
invocation syntax. Key points concerning abstract properties:

• May not be static


• An abstract inherited property can be overridden in a derived class by including a
property declaration that uses the override method.

An abstract class has to provide implementations for all of its interface members.
Sample:
// Abstract classes
using System;

abstract class MyAbstractC // Abstract class


{
protected int iHours = 40;
protected int iWage = 25; // A VB developer? *smirk*

// Abstract method
public abstract void DoOvertime();

// Abstract property
public abstract int GetHours
{
get;
}

// Abstract property
public abstract int GetWage
{
get;
}
}

// Derived from abstract class, MyAbstractC


class MyDerivedC: MyAbstractC
{
// overriding the method
public override void DoOvertime()
{
iHours = 50;
iWage = 38;
}

// overriding the property


public override int GetHours
{
get
{
return iHours;
}
}

// overriding the property


public override int GetWage
{
get
{
return iWage;
}
}

public static void Main()


{
// instance of derived class
MyDerivedC dC = new MyDerivedC();

dC.DoOvertime();
Console.WriteLine("Hours worked = {0},
Wage earned = {1}", dC.GetHours, dC.GetWage);

// Pause output window


Console.ReadLine();

Output: Hours worked = 50, Wage earned = 38

Anda mungkin juga menyukai