Search code examples
javaabstract-data-type

What are Abstract data types in algorithms and why do we need them?


I would also like to quote from a source from where i read and could not understand.

We all know by default, all primitive datatypes (int, float etc) support basic operations such as addition and subraction. The system provides the implementation for the primitive datatypes. For userdefined types we need to define operations. The implementation of these algorithms is done when we use them. That means, user defined datatypes are defined along with their operations.

To simplify the process of solving problems, we combine dataStructures along with their operations and call it as AbstractDataType.

Can anyone explain a good example of it and to the context of real world too? Why u need them?

Source Narasimha Karumanchi book DataStructures and Algorithms


Solution

  • Good question!

    In terms of application infrastructure and design, abstract data types are useful in order to have a clean and understandable hierarchy of classes and data models. As you asked for a practical example, take any application that uses a database: say an online eshop. Primitive data types are useful, of course, say we use doubles to store prices, ints to store the number of items and strings to display and store item names / descriptions, but how do we deal with the basket/cart? Easiest and most recommended way is to create an abstract representation of the cart via a separate class, say shoppingCart, which will contain its properties:

    class shoppingCart{
    int numOfItems;
    double totalPrice;
    List<Product> products;
    etc.
    }
    

    Also, we would need classes to represent the Products and categories such as:

    class Product{
    double price;
    string name;
    etc.
    }
    

    Think of any abstract data type that you create as your own objects, with their own methods and so on.

    We would use abstract classes to define general behavior of certain subclasses that extend them, such as: abstract class Vehicle and classes Car, Bike that extend Vehicle. The structure would be:

     abstract class vehicle{
    public void drive();
    public int getNumberOfWheels();
    }
    

    This way we make sure that all instances of Car and Bike will implement the 2 methods listed in the abstract class vehicle:

    class car extends vehicle{
    //we have to implement the 2 methods and provide an implementation for it
    }
    

    Another developer would like to create a new type of vehicle (say "plane"), so he could now see that he has to implement the 2 methods no matter what.

    I hope I could help you.