Search code examples
javainterfaceabstract-classabstractiondata-hiding

JAVA - Abstraction


I am little confused about abstraction in java.

I have checked many pages stating that abstraction is data hiding(Hiding the implementation).

What I understand about abstraction is it is 'partial implementation'. Just define what you are going to need in an abstract class/interface and afterwards extend/implement them and add your own functionality.

What I don't understand is how this is a data hiding? You are going to get access to the code once you implement the class/interface and you will modify it according to your need.

I have checked many questions, articles on this but still confused about this.

Any help is appreciated. Thanks.


Solution

  • Maybe an example help you better. Suppose you want to implement a Graph class which may be have adjacency list or adjacency matrix to represent its nodes. So in abstract you want to "addNode" "addEdge" to this graph at least:

    public abstract class Graph
    {
        public abstract int addNode();
        public abstract void addEdge(int from, int to);
    }
    

    Now you can extend two classes:

    public class GraphAdjList extends Graph
    {
        private Map<Integer,ArrayList<Integer>> adjListsMap;
        public int addNode()
        {
            //list based implementation 
        }
        public void addEdge(int from, int to)
        {
            //list based implementation
        }
    }
    
    public class GraphAdjMatrix extends Graph
    {
        private int[][] adjMatrix;
        public int addNode()
        {
            //matrix based implementation 
        }
        public void addEdge(int from, int to)
        {
            //matrix based implementation
        }
    }
    

    when you call either of addEdge from these two classes you don't have to worry about the data structure behind it, you just know that you get the result you needed so for example:

    Graph g1,g2;
    g1 = new GraphAdjList();
    g2 = new GraphAdjMatrix();
    
    g1.addEdge(1,2);
    g2.addEdge(1,2);
    

    through polymorphism you call two different functions but get the same result as client of the Graph.

    Another real life example would be car brakes. As a car client, the manufacturer gives you a pedal to push without knowing what is the implementation of the brake in the back-end. It can be a drum-brake or disc-brake implementation in the back. All you need is to push the brake!