Pages

Friday 20 September 2019

Default method

Default Methods
  1. In Java 1.8v onwards, you can also define the default method inside the interface.
  2. You can define the default method using the keyword default.
  3. Default methods are by default available to all implementation classes. Based on our business requirement implementation class can use these default methods directly or override.
  4. You can't override object class methods as default methods inside interface otherwise you will get a compilation error. Because you know Object class methods are by default available to each class/interface hence it is not required to override.
  5. If you try to override Object class methods in the interface, you will get compiler error.
Note: You can't define the default method inside the concrete class and abstract class, otherwise compilation error.

Let's understand the above concept through examples.
Example1:
  1. public default void methodOne(){
  2. System.out.println("methodOne");
  3. }
  4. public default int methodOne(int a){
  5. return 10;
  6. }
Example2:
  1. interface InterA{
  2. public default int add(int a, int b){
  3. return a+b;
  4. }
  5. }
  6. class Test implements InterA{
  7. public static void main(String[] args){
  8. Test t = new Test();
  9. t.add(10,20);
  10. }
  11. }
Example3:
  1. interface InterA{
  2. public default void methodOne(){
  3. System.out.println("methodOne of InterA");
  4. }
  5. }
  6. class Test implements InterA{
  7. public void methodOne(){
  8. System.out.println("methodOne of Test");
  9. }
  10. public static void main(String[] args){
  11. Test t = new Test();
  12. t.methodOne();//methodOne of Test
  13. }
  14. }
Example4:
  1. interface InterA{
  2. public default String toString(){
  3. return null;// compilation error, you can't override Object class methods.
  4. }
  5. }
Default method w.r.t Inheritance
If two interfaces contain default method with same method signature then you will get ambiguity problem(diamond problem) in implementation class.To overcome this problem compulsory you should override default method in the implementation class otherwise you will get compilation error.

Example:
  1. interface A{
  2. default void methodOne(){
  3. System.out.println("Interface A default method");
  4. }
  5. }
  6. interface B{
  7. default void methodOne(){
  8. System.out.println("Interface A default method");
  9. }
  10. }
  11. class Test implements A,B{}//compilation error
Q. How to override default method?
In the implementation class, you can override the default method by removing keyword default and abide by overriding rules.

Example:
  1. class Test implements A,B{
  2. public void methodOne(){
  3. System.out.println("Override default method");
  4. //You can also do as below
  5. A.super.methodOne();
  6. B.super.methodOne();
  7. }
  8. public static void main(String args){
  9. Test t = new Test();
  10. t.methodOne();
  11. }
  12. }