javaoopinheritancemethod-hiding

Inherit hidden methods


I have an interface that has 4 methods and a class that implements the interface. Here comes the question: "How can I inherit from the interface only 2 of those methods and my class don't became abstract?"

interface Class1 {
    void method1();
    void method2();
    void method3();
    void method4();
}


public class Class2 implements Class1 {

    @Override
    public void method1() {

    }

    @Override
    public void method2() {

    }
}

Solution

  • You have to get tricky, and you have to lookup why this works, especially if it's an interview question. It's basically for compatibility (the default methods in the interface), and requires Java 8.

    public interface One {
      void method1();
      void method2();
      void method3();
      void method4();
    }
    
    public interface Two extends One{
      default void method1(){}
      default void method2(){}
    }
    
    public class Three implements Two{
    
      @Override
      public void method3() {}
    
      @Override
      public void method4() {}
    
    }
    

    Non-abstract Three.class implements method3 and method4 of One.class without defining method bodies for method1 and method2. Method1 and Method2 are defined with default implementations in interface Two.class.