Abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can also be achieved with Interface.
Refer the below URL to achieve abstraction using Access modifiers or Abstract Class.
https://itsforlavanya.blogspot.com/2020/08/abstraction-abstraction-in-c.html
https://itsforlavanya.blogspot.com/2020/08/abstraction-using-abstract-class.html
Interface – It is 100% Abstract class, it contains only abstract methods
and properties, no implementation nor no regular methods will be present inside
interface.
Example -
// interface
interface IVehicle
{
string vehicleColor { get; set; } // interface properties
void twoWheeler(); // interface method (does
not have defenition/body)
void start(); // interface method (does not have a
defenition/body)
}
Use letter “I” in front of Interface Name to make everyone know
easily that it is an Interface.
Similar to Abstract Class, we cannot create object of Interface as well
IVehicle obj = new IVehicle(); // Error -Cannot Create Instance of Abstract Class or
Interface "Vehicle"
Now, to access the methods inside the interface, interface must be inherited
by another class, the definition for interface methods is defined by the class
that inherits the interface.
Note – Unlike abstract class we never use override keyword
here before method name
namespace Abstraction
{
// interface
interface IVehicle
{
string vehicleColor { get; set; } // interface properties
void twoWheeler(); // interface method (does
not have defenition/body)
void start(); // interface method (does not have a
defenition/body)
}
public class TwoWheeler : IVehicle
{
public string
vehicleColor { get; set; }
public void start()
{
Console.WriteLine("Starting the twoWheeler");
Console.WriteLine("My color is {0}",
vehicleColor);
}
public void
twoWheeler()
{
Console.WriteLine("I have 2 wheels");
}
}
public class Program
{
public static void main()
{
TwoWheeler obj = new TwoWheeler();
obj.vehicleColor = "Black";
obj.start();
obj.twoWheeler();
}
}
}
Note -
1. Interface can contains properties and methods but not variables and fields.
2. Interface members are by default abstract and public.
3. Interface cannot contain Constructor, as we cannot create object for interface.
4. When we inherit the interface, all the methods and properties inside the interface should be implemented, else we will get an error asking to implement all the methods inside interface.
Conclusion – In Interface we have not shown the implementation of
twoWheeler and start method, this way we are hiding the implementation from outside world,
and showing only required information.
0 comments: