Hide your public implementations of Interface from rest of the world

Most of the time you're building a real world application you have to use a lot of interface, and now and then they contains public method signature which you don't want to be exposed to the developer using your API or subclassing your class or creating instance of the class.

Let's take a look at this code

  
public interface OnFinishedCoding {  
    public void eat();
    public void sleep();
}

Let's look at its implementation

  
public class Main implements OnFinishedCoding{  
    public Main() {
        Programmer programmer = new Programmer();
        programmer.setOnFinishedCodingListener(this);
    }

    @Override
    public void eat() {
        System.out.println("I'm eating");
    }

    @Override
    public void sleep() {
        System.out.println("I'm sleeping");
    }
}

Now, if someone just instantiate your class the public method will be available for calling. If you want that behaviour it's fine but if you want to hide that implementation you can just do anonymous implementation of the interface and make it private. This encapsulation technique will hide the public implementation from rest of the world.

Hiding the implementation

  
public class Main{

    public Main() {
        Programmer programmer = new Programmer();
        programmer.setOnFinishedCodingListener(listener);
    }

    private OnFinishedCoding listener = 
    new OnFinishedCoding() {
        @Override
        public void eat() {

        }

        @Override
        public void sleep() {

        }
    };
}

Happy Coding :)

comments powered by Disqus