-1

In java 8, got two interfaces with same name method.

First method don't have body

interface Interface01 {
    void method();
}

and other have default body

interface Interface02 {
    default void method() { 
        System.out.println("This is from: Interface02 - method()");
    }
}

How to call second method() in first @overriden method(). Is it possible?

class ChildClass implements Interface01, Interface02 {
    
    public void method() { //override method from Interface01
        
        method();          // calling method from Interface02
    }
}

Is this possible, reference to interface02.method()?

acakojic
  • 306
  • 2
  • 11
  • 1
    Have you tried actually creating `Interface02` and seeing if it compiles? – Jacob G. Oct 28 '20 at 14:27
  • 2
    `Interface02.super.method();` (now where is that duplicate.. found it [Explicitly calling a default method in Java](https://stackoverflow.com/q/19976487)) – Pshemo Oct 28 '20 at 14:28
  • @Pshemo not working by the way.. – acakojic Oct 28 '20 at 14:31
  • 1
    regarding @JacobG. comment, you may find your IDE gives you another hint with respect to Interface02.method(). Mine did. Haven't followed java for the last few years so it's cool to see this feature. – Michael Welch Oct 28 '20 at 14:33
  • 1
    @acakojic Are you sure? Works fine for me: https://ideone.com/wviocU – Pshemo Oct 28 '20 at 14:36
  • 1
    acakojic, you forgot the `default` keyword on Interface02.method() which may account for why it's not working for you. Like @Pshemo it works fine for me. – Michael Welch Oct 28 '20 at 14:36
  • @Pshemo Yup this is working my bad. Need to change public to default method(){}. – acakojic Oct 28 '20 at 14:37
  • 1
    @MichaelWelch I'm learning java-8 right now. Was writting java-7.. I'm too old for this.. My brain got open two many tabs – acakojic Oct 28 '20 at 14:40

2 Answers2

1

It's weird syntax, but it is available:

class ChildClass implements Interface01, Interface02 {
    
    public void method() { //override method from Interface01
        
        Interface02.super.method();          // calling method from Interface02
    }
}

You can use this here. You can also use it if both I1 and I2 have a default method - then your ChildClass wouldn't compile either (javac forces you to explicitly pick which of the two impls you want, or if you want to write an entirely new one - that's because java, by the design, does not want the order in which you listed your interfaces to change what your code means).

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
1
class ChildClass implements Interface01, Interface02 {
    
    public void method() { //override method from Interface01
        
        Interface02.super.method();          // calling method from Interface02
    }
}
Rubydesic
  • 3,386
  • 12
  • 27