abstract
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:
Key points concerning Abstract methods:
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
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.
public abstract void MyMethod(); // 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.
- 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 must provide implementation for all interface members.
An abstract class that implements an interface might map the interface methods onto abstract methods. For example:
Example
In this example, the classMyDerivedC
is derived from an abstract classMyBaseC
. The abstract class contains an abstract method,MyMethod()
, and two abstract properties,GetX()
andGetY()
.
// abstract_keyword.cs // Abstract Classes using System; abstract class MyBaseC // Abstract class { protected int x = 100; protected int y = 150; public abstract void MyMethod(); // Abstract method public abstract int GetX // Abstract property { get; } public abstract int GetY // Abstract property { get; } } class MyDerivedC: MyBaseC { public override void MyMethod() { x++; y++; } public override int GetX // overriding property { get { return x+10; } } public override int GetY // overriding property { get { return y+10; } } public static void Main() { MyDerivedC mC = new MyDerivedC(); mC.MyMethod(); Console.WriteLine("x = {0}, y = {1}", mC.GetX, mC.GetY); } }
Output
No comments :
Post a Comment