Home > Mobile >  what is the meaning of hiding the implementation by using abstract class?
what is the meaning of hiding the implementation by using abstract class?

Time:09-02

I am trying to find the real solution to using abstract classes to hide the implementation means why we need to use an abstract class to hide the implementation suppose we are working on a big project and of course, our code will be shared with other developers means suppose I have created a class and that class could be used by other developers and if someone else means developer wants to use my class I will give them a library of my class and they will import my class and they will create the object of my class that`s set here I want to know that here developer who is creating a class object is not able to see my class implementation then why we need to use an abstract class?

CodePudding user response:

Let's imagine that we have the following class of Pizza:

public abstract class Pizza
{
    public abstract decimal Cost();
}

And then imagine you want to build some web site where you can show all prices of all pizzas in your city. So users can compare costs of pizza of all pizza stores.

Well, let's create PizzaComparison class where we can get price of different Pizza different cafes and then we need to store somewhere this pizza's cost:

public class PizzaComparison
{
    public void SaveCurrentPrice(Pizza pizza) 
    {
        decimal price = pizza.Cost();
        // then you can save it to database and show all prices for users
    }
}

Let's see more accurate the above code. How does it hide the implementation? Method SaveCurrentPrice of class PizzaComparison does not know anything about of a concrete implementation of Cost() method of Pizza class. It only knows some abstract details like that method should return decimal value and this value should be a price of pizza. But where is implementation details? Implemetation details are placed and hidden in subclasses, derived classes that inherit from Pizza class.

  •  Tags:  
  • oop
  • Related