Search code examples
javaabstraction

How we achieve abstraction in java?


As per definition, abstraction is hiding the implementation detail and revealing only the functionality. But exactly, what, where and which part we are hiding?

AFAIK the following program is an example of Abstraction:

public interface ToBeImplemented { 

   public string doThis();
}

public class Myclass implements ToBeImplemented {

@override
public string doThis() {

//Implementation

 return null;
 }
}

If I am wrong and this is not abstraction then what is the correct example of Abstraction?


Solution

  • In the above example you can write something like this:

    public interface ToBeImplemented { 
    
        public string doThis();
    }
    
    public class ImplementationA implements ToBeImplemented {
    
        @override
        public string doThis() {
    
        //ImplementationA of doThis
    
        return null;
        }
    }
    
    public class ImplementationB implements ToBeImplemented {
    
        @override
        public string doThis() {
    
            //ImplementationB of doThis
    
            return null;
        }
    

    }

    Then you can have another class, and a main method for example:

    class SomeClass{
    
        public static void main(String[] args) {
    
            ToBeImplemented someImplementation;
    
            //now you can pick an implementation, based on user input for example
            if (userInput == something) 
               someImplementation = new ImplementationA();
            else
               someImplementation = new ImplementationB();
    
            //do some staff
    
            //Regardless of the user input, main method only knows about the
            //abstract "ToBeImplemented", and so calls the .doThis() method of it
            //and the right method gets called based on the user input.
            someImplementaion.doThis();
            //at That
    
        }
    
    }
    

    The abstraction is that you can declare a ToBeImplemented reference, and then assign to it either ImplementationA, or ImplementationB (and possibly any other implementation). But you write your code against the abstract ToBeImplemented, and let some conditions decide what the right implementation of ToBeImplemented (and, as a result doThis()) should be called.