not implementing all of the methods of interface. is it possible?

前端 未结 10 1965
挽巷
挽巷 2020-11-28 03:33

Is there any way to NOT implement all of the methods of an interface in an inheriting class?

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 04:29

    You can do that in Java8. Java 8 introduces “Default Method” or (Defender methods) new feature, which allows a developer to add new methods to the Interfaces without breaking the existing implementation of these interfaces.

    It provides flexibility to allow Interface define implementation which will use as default in the situation where a concrete Class fails to provide an implementation for that method.

    interface OldInterface {
        public void existingMethod();
    
        default public void DefaultMethod() {
            System.out.println("New default method" + " is added in interface");
        }
    }
    //following class compiles successfully in JDK 8
    public class ClassImpl implements OldInterface {
        @Override
        public void existingMethod() {
            System.out.println("normal method");
    
        }
        public static void main(String[] args) {
            ClassImpl obj = new ClassImpl ();
            // print “New default method add in interface”
            obj.DefaultMethod(); 
        }
    }
    

提交回复
热议问题