Tutorial: 14 - Abstraction in C#
Abstraction
Exposing
only information which is relevant and essential to user and hiding
certain details from the user is referred as Abstraction. Abstraction
can be achieved using either interfaces or abstract classes.
Example
Consider an example of ATM. A user enters his card in ATM, then enters PIN Code. After accessing the account, he enters the amount which is required by him to withdraw and lastly he gets his amount from ATM. The user doesn't know how this ATM works internally all he care is to operate the machine using touch panel or keypad on ATM. This is an example ATM machine.
Now to achieve abstraction we will use abstract class.
Abstract Class
Abstract classes are special classes marked with keyword abstract and they cannot be instantiated meaning you cannot create their objects. A method which is marked abstract does not have its implementation. In order to create an abstract class or abstract method you have to use abstract keyword e.g.
public abstract void hello();
//abstract method
public abstract Student
//abstract method
There are some points you should keep in mind for an abstract class.
- Abstract classes are only inherited and you have to provide implementation of inherited method available in abstract class..
- A user must use the override keyword before the method which is declared as abstract in child class, the abstract class is used to inherit in the child class.
- Structures cannot inherit abstract classes.
- There are no constructors or destructors in abstract classes
- You can add a non abstract method in it and provide its implementation.
- It does not supports multiple inheritance.
- It cannot be static.
- If all the methods in a class are abstract, then class is called pure abstract class.
- You cannot set an abstract class as sealed class.
Now we will see an example how to implement abstraction in C#
public
abstract
class
Human
{
public
abstract
void
hello
();
//Abstract Method
}
// Student class inheriting Human class
public
class
Student : Human
{
// Overriding method using override keyword
public
override
void
hello()
{
Console.WriteLine(
"In Student class"
);
}
}
public class Employee : Human
{
// Overriding method using override keyword
public override void hello()
{
Console.WriteLine("In Employee class");
}
}
public static void main()
{
Student s = new Student();
s.hello();
Employee e = new Employee();
e.hello();
}
Output:
In Student class
In Employee class
In above program, we have created a class named Human and there are other two classes with name Student and Employee. Both classes are inheriting Human class and then they are implementing the method hello with each class having its own implementation. Keep in mind that abstract classes can also work with get and set methods.
No comments:
Post a Comment