Ticker

6/recent/ticker-posts

C# (C Sharp) - Abstract Methods | Abstract Classes

C# (C Sharp) - Abstract Methods | Abstract Classes 

  • 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. 

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. 

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() 

//code 

}

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!";

}


"abstract class in c#"

"abstract method in c#"

"abstract class and interface in c#"

"c# abstract class tutorial"

"c# abstract vs interface"

"abstract class constructor c#"