Abstract Classes and Methods
Data abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can be achieved with either Abstract classes or interfaces ( which you will learn more about in the next chapter ).
The Abstract keyword is used for classes and methods :
. Abstract class : is a restricted class that cannot be used to create objects ( to access it, it must be inherited from another class).
. Abstract method : can only be used in an abstract class, and it does not have a body. The body is provided by the derived class ( inherited from ).
An abstract class can have both abstract and regular methods.
abstract class Animal
{
public abstract void animal sound ( );
public Void sleep ( )
{
Console.WriteLine (” Zzz”);
}
}
From the example above, it is not possible to create an object of the Animal class :
Animal my Obj = new Animal ( ); //will generate an error ( cannot create an instance of the abstract class or interface ‘ Animal’)
Example :-
// Abstract class
abstract class Animal
{
// Abstract method ( does not have a body )
public abstract void animal Sound ( );
// Regular method
public void sleep ( )
{
Console.WriteLine ( “Zzz”);
}
}
// Derived class ( inherit from Animal )
class Pig: Animal
{
public override void animal sound ( )
{
// The body of animalSound ( ) is provided here
Console.WriteLine (” The pig says : wee wee “);
}
}
class program
{
static void Main ( string [ ] args)
{
pig myopic = new Pig ( ); // create a Pig object
myPig. animalSound ( ); // call the abstract method
myPig . sleep ( ); // call the regular method
}
}
program.cs
Using System;
namespace MyApplication
{
// Abstract class
abstract class Animal
{
// Abstract method ( does not have a body )
public abstract void animalSound ( );
Result
The pig says : Wee wee
Zzz