Abstraction :-
Abstraction is one of the principle of object oriented programming. It is used to display only necessary and essential features of an object to ouside the world.Means displaying what is necessary and encapsulate the unnecessary things to outside the world.Hiding can be achieved by using "private" access modifiers.
Note- Outside the world means when we use reference of object then it will show only necessary methods and properties and hide methods which are not necessary.
Implementation of Abstraction:-
To implement abstraction let's take an example of a car. We knows a car, Car is made of name of car, color of car, steering, gear, rear view mirror, brakes, silencer, exhaust system, diesal engine, car battery, car engine and other internal machine details etc.
Necessary things means compulsary to know before starting a car
- Name of Car
- Color of Car
- Steering
- Rear View Mirror
- Brakes
- Gear
Unnecessary things means not that compulsary to know for a Car rider
- Internal Details of a Car
- Car Engine
- Diesal Engine
- Exhaust System
- Silencer
Now above same thing let me put in the coding style using C\
public class Car
private string _nameofcar = "My Car";
private string _colorofcar = "Red";
public string NameofCar
set
_nameofcar = value;
}
get
return _nameofcar;
}
}
public string ColorofCar
set
_colorofcar = value;
}
get
return _colorofcar;
}
}
public void Steering()
Console.WriteLine("Streering of Car");
}
public void RearViewMirror()
Console.WriteLine("RearViewMirror of Car");
}
public void Brakes()
Console.WriteLine("Brakes of Car");
}
public void Gear()
Console.WriteLine("Gear of Car");
}
private void InternalDetailsofCar()
Console.WriteLine("InternalDetailsofCar of Car");
}
private void CarEngine()
Console.WriteLine("CarEngine of Car");
}
private void DiesalEngine()
Console.WriteLine("DiesalEngine of Car");
}
private void ExhaustSystem()
Console.WriteLine("ExhaustSystem of Car");
}
private void Silencer()
Console.WriteLine("Silencer of Car");
}
}
As you can see from above code that necessary methods and properties exposed by using "public" access modifier and unnecessary methods and properties (not compulsary) hidden by using "private" access modifier.
As you see to achieve abstraction we used access modifier "public" to expose some methods and properties to outside the class or world.
As you see to achieve abstraction we used access modifier "private" to hide some methods and properties from outside the class or world.
Finally lets check by creating an object of above class "Car" in our main program of a console application and by using object lets see weather we are getting all exposed necessary methods and properties.
class Program
static void Main(string[] args)
Car objCar = new Car();
}
}
Conclusion:-
Sucessfully we have exposed necessary methods and properties to outside the world or class. This is how we need to implement abstraction or we can achieve abstraction in our code or application.