Can an interface method have a body?

后端 未结 3 1553
遥遥无期
遥遥无期 2020-12-04 15:30

I know that an interface is like a 100% pure abstract class. So, it can\'t have method implementation in it. But, I saw a strange code. Can anyone explain it?

3条回答
  •  [愿得一人]
    2020-12-04 15:48

    For java version 7 or below, similar functionally you can achieve using nested class declared within interface body. and this nested class implements outer interface.

    Example:

    interface I1{
        public void doSmth();
    
        class DefaultRealizationClass implements  I1{
    
            @Override
            public void doSmth() {
               System.out.println("default realization");
            }
        }
    }
    

    How do we use it in our code?

    class MyClass implements I1{
    
        @Override
        public void doSmth() {
             new I1.DefaultRealizationClass().doSmth();
        }   
    }
    

    Therefore default implementation encapsulated within interface.

提交回复
热议问题