Information About Implementing Interfaces

Asked 2 years ago, Updated 2 years ago, 35 views

public interface a{
 default void sample() {
 System.out.print("A");
}
}

public interface extensions a {

}

public interface components b {
 @ Override
 public void sample();
  a.super.sample();
  System.out.print("java");
}
}
}

public class Main {
 public static void main(String[]args) {
 aa = new c();
 a.sample();
}
}

I have a question about the above code.

public interface extensions a{

}

b class implements a, but does not implement sample() I think it's the wrong class to implement the interface, but I'm wondering because there are no compilation errors.
Please let me know if it is possible without implementing sample() in the b class.

The following rules apply to the interface:

java

2022-09-30 20:23

1 Answers

The code in the questionnaire that eliminates the compilation error with as much intention as possible is as follows:

public interface a{
    default void sample() {
        System.out.print("A");
    }
}
public interface extensions a{

}
public class components b{
    @ Override
    public void sample() {
        b.super.sample();
        System.out.print("java");
    }
}
public class Main {
    public static void main(String[]args) {
        aa = new c();
        a.sample();
    }
}

If you answer on the assumption that the actual code you are expecting is the one above,

b class implements a, but does not implement sample() I think it's the wrong class to implement the interface, but I have no compilation errors and I'm wondering.

First, b is an interface, not a class.
Also, even if b is a class that implements a, sample() is implemented by default on the a interface, so implementation in b can be omitted.

Therefore,

Please let me know if it is possible without implementing sample() in the b class.

The answer to is yes.

Class implementing the interface must implement the declared method.

For , the default method was introduced in Java 8.
If the default method provides a default implementation, override is no longer required on the implementation class side.

A default method(snip)provides a default implementation for any class that implements the interface without overriding the method.


2022-09-30 20:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.