DEV Community

Chhavi Joshi
Chhavi Joshi

Posted on

Default and Private methods in interface

We know that interface is like a blueprint class that gives us a hollow structure or scaffold that needs to be used in other classes, by just declaring the methods and not implementing it in the interface. This gives freedom for every class to implement the same method in its own manner, whenever we implement the inteface.

But one thing must be kept in mind that when we derive a class from an interface by implementing it we must either define all the methods present in the interface or we must make the class abstract. This is because when we implement an interace in a class all the methods that were a part of interface earlier are now indirectly present in the class as well, and so if a method is not defined among the existing methods it is present as an abstract method in the class and we already know that even if a class contains a single abstract method it must be abstract itself.

So problem arises when we want to update the interface i.e. add a new method in interface. Earlier it was not possible as when we update the interface by adding even a single method to it, every class that implemented the interface must also be updated, so to solve this problem default methods were introduced.

In my previous post I had already posted this interface Shape where the methods were dimensions() and area(), these were the fields that would be different for every shape but suppose later I thought of adding a method show() that would print "I'm a shape", so i could make this a default method. You'll understand it further by going through its properties mentioned as follows:

  • They must be defined in the interface itself.
  • It's not necessary to mention a default method for a class to be concrete.
  • If we want to use it for other purpose in a class implementing the interface we can simply override the default method.

In this manner default methods are used to add new method without breaking the old code

Now talking about private methods, these are like helper methods used for supporting the default method. Or these can be used when the logic of the default method becomes very long so these can be seperately made and then be called inside the default method like I did in the above code.

properties of private method:

  • Unlike default methods they can only be used in the interface as they are private.
  • These cannot be overridden.
  • These are helper methods of the default method.
  • Any object cannot call them directly because of private access specifier.

Top comments (0)