Object Oriented Programming

Abstract Methods and Classes in C#

Abstract methods, similar to methods within an interface, are declared without any implementation. They are declared with the purpose of having the child class provide implementation. They must be declared within an abstract class.

A class declared abstract may or may not include abstract methods. They are created with the purpose of being a super class.


Syntax
modifier abstract class className {
    //declare fields (which can contain assignments)
    modifier dataType variableName;
    //declare methods
    modifier abstract dataType methodName();
}

modifier class childClass : className {
    override modifier dataType methodName(){}
}

Notes

Abstract classes and methods are declared with the 'abstract' keyword. Abstract classes can only be extended, and cannot be directly instantiated.

Abstract classes provide a little more than interfaces. Interfaces do not include fields and super class methods that get inherited, whereas abstract classes do. This means that an abstract class is more closely related to a class which extends it, than an interface is to a class that implements it.

Modifiers can only be 'public' or 'protected'. The modifier in the child class overriding a method must be the same as the modifier in the parent abstract class.


Example
public abstract class Animal 
{
	protected string name;  
	public abstract string sound(); //all classes that implement Animal must have a sound method
} 

public class Cat : Animal 
{  
	public Cat() 
	{
		this.name = "Garfield";        
	}    
	
	override public string sound()
	{ //implemented sound method from the abstract class & method
		return "Meow!";
	}
} 

See Also
Related

Inheritance
Interfaces

Documentation

abstract (C# reference)

Add to Slack

< Interfaces   |   Inheritance >

© 2019 SyntaxDB. All Rights Reserved.