Search code examples
javaoopabstraction

Seeing the implementation details in abstraction


Basic Definition of abstraction is hiding the implementation complexity of the methods and showing the functionality . Although while working with code (while I was using eclipse) there is an option of opening the implementation for the abstract methods.

For eg:-

I was trying to open the implementation for BufferedReader was able to see through many implementations.

So how we are hiding the complexity when we are able to see the implementation.

Where am I going wrong conceptually?


Solution

  • Abstaction does not mean hiding the implementation details from you phisically. You will still see all the implementation lines of the implenmented abstract methods unless you have your eyes. Abstraction means hiding the implementation details from the one how is intended to use the method in their code.

    Assume you're writing the class that approximates the derivative of a function. Of which function? That does not matter if you think of a function as of the abstraction. You do not care of what the function would be. You just define some basic principals of how that function should be implemented. It should take a double value and it should return a double value.

    This conception hides the function implementation complexity from you as from the designer of your class. You can now proceed with implentaion your part of job. You might write the following class:

    public abstract class DerivativeApprox {
    
        abstract double func(double x);
    
        double eps = 0.0;
    
        DerivativeApprox(double eps){
            this.eps = eps;
        }
    
        public double eval(double xPoint){
            return (func(xPoint + eps) - func(xPoint - eps)) / (2 * eps);
        }
    }
    

    Now anyone would be able to use your class in the following way (taking the responsibility of implementing any particular function they want to estimate the derivative)

    public static void main(String[] args) {
    
        DerivativeApprox cosDerApprox = new DerivativeApprox(0.0001) {
            @Override
            double func(double x) {
                return Math.cos(x);
            }
        };
    
        DerivativeApprox sinDerApprox = new DerivativeApprox(0.0001) {
            @Override
            double func(double x) {
                return Math.sin(x);
            }
        };
    
        System.out.println("Cos'(pi) = " + cosDerApprox.eval(Math.PI));
        System.out.println("Cos'(pi/2) = " + cosDerApprox.eval(Math.PI / 2));
    
        System.out.println("Sin'(pi) = " + sinDerApprox.eval(Math.PI));
        System.out.println("Sin'(pi/2) = " + sinDerApprox.eval(Math.PI / 2));
    
    }
    

    Hope this explanation will help ypu to proceed with OOP learning.