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

前端 未结 10 1920
挽巷
挽巷 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

    If you want an instantiable class, it is not possible. You may try to define an abstract class, though.

    0 讨论(0)
  • 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(); 
        }
    }
    
    0 讨论(0)
  • 2020-11-28 04:30

    If you try to implement an interface and you find yourself in a situation where there is no need to implement all of them then, this is a code smell. It indicates a bad design and it violates Liskov substitution principle. Often this happens because of using fat interface.

    Also sometimes this happens because you are trying to implement an interface from an external dependency. In this case, I always look inside the source code to see if there is any implementation of that interface which I can either use it directly or subclass it and override methods to my needs.

    0 讨论(0)
  • 2020-11-28 04:31

    We can override all the interface methods in abstract parent class and in child class override those methods only which is required by that particular child class.

    Interface

    public interface MyInterface{
        void method1();
        void method2();
        void method3();
    }
    

    Abstract Parent class

    public abstract class Parent implements MyInterface{
    @Override
    public void method1(){
    
    }
    @Override
    public void method2(){
    
    }
    @Override
    public void method3(){
    
    }
    }
    

    In your Child classes

    public class Child1 extends Parent{
        @Override
        public void method1(){
    
        }
    }
    
    
    
    
    public class Child2 extends Parent{
        @Override
        public void method2(){
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题