Default Method is one of the features of Java 8. Default Method is
More details on the default methods and its use in Java will be explained in the next post.
Happy Learning!!!!
- A method - which has a keyword default before it
- Has to be defined only in Interface
- Must be implementation.
- Can be overridden in Implemented Classes but has to be defined without default keyword.
- An Interface can have multiple default methods
Example
- As mentioned earlier, default method is a method with implementation in an Interface
public interface AInterface { public default void print() { System.out.println("Default Method in Interface A"); } }
- If a class implements it, then it may or may not override the default method along with it's own methods.
public class AImplementation implements AInterface { public void otherMethod() { System.out.println("New Method Defined in AImplementation"); } }
- Calling a default is same as like other methods as below
AImplementation a = new AImplementation(); a.print(); a.otherMethod();
- As multiple interfaces can be implemented by one class, but there is a probability of same default method with the same name, defined in both interfaces. Let's say another interface with a default method print like below
public interface BInterface { default void print() { System.out.println("Default Method in Interface B"); } }
- Now, if a class implements both AInterface and BInterface, which has same default method print, then compiler throws an error saying "Duplicate default methods named print with the parameters () and () are inherited from the types BInterface and AInterface". So, print method has to be overridden in the implemented Class like below
public class CImplementation implements AInterface, BInterface { @Override public void print() { System.out.println("Default Method in Interface A"); } }
More details on the default methods and its use in Java will be explained in the next post.
Happy Learning!!!!
No comments:
Post a Comment