Difference between revisions of "Abstraction"
From JholJhapata
(Created page with "'''Abstraction''' is the process representing essential features without including background details, to reduce the complexity for the users. Abstraction can be achieved with...") |
|||
| Line 1: | Line 1: | ||
'''Abstraction''' is the process representing essential features without including background details, to reduce the complexity for the users. Abstraction can be achieved with either abstract classes or interfaces. | '''Abstraction''' is the process representing essential features without including background details, to reduce the complexity for the users. Abstraction can be achieved with either abstract classes or interfaces. | ||
| − | |||
== Abstract class & Abstract method == | == Abstract class & Abstract method == | ||
'''Abstract''' keyword is used with classes and methods: | '''Abstract''' keyword is used with classes and methods: | ||
Revision as of 06:26, 5 January 2020
Abstraction is the process representing essential features without including background details, to reduce the complexity for the users. Abstraction can be achieved with either abstract classes or interfaces.
Abstract class & Abstract method
Abstract keyword is used with 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.
abstract class Software
{
// Abstract method (does not have a body)
public abstract void addIcon();
// Regular method
public void defaltPath()
{
Console.WriteLine("c:");
}
}
// Derived class (inherit from Software)
class WinZip : Software
{
public override void addIcon()
{
// The body of addIcon() is provided here
Console.WriteLine("Desktop");
}
}
class Program
{
static void Main(string[] args)
{
WinZip myWinZip = new WinZip(); // Create a WinZip object
myWinZip.defaltPath(); // Call the abstract method
myWinZip.addIcon(); // Call the regular method
}
}
Interface
An interface is a completely "abstract class", which can only contain abstract methods and properties (with empty bodies). Interface is another way to achieve abstraction in C#.
interface Software
{
// Abstract method (does not have a body)
void addIcon();
// Regular method
void defaltPath();
}
// Derived class (inherit from Software)
class WinZip : Software
{
public void addIcon()
{
// The body of addIcon() is provided here
Console.WriteLine("Desktop");
}
public void defaltPath()
{
Console.WriteLine("c:");
}
}
class Program
{
static void Main(string[] args)
{
WinZip myWinZip = new WinZip(); // Create a WinZip object
myWinZip.defaltPath(); // Call the abstract method
myWinZip.addIcon(); // Call the regular method
}
}