0

please explain why? can't find any good source

interface ABCD {
    default void print() {}
    static void print_static() {}
}

interface B extends ABCD{
    static void print() {}//error, why?
    default void print_static() {}//fine, why?
}

Answer: @AdolisPali Becase the default method print is inherited from ABCD, so it's in interface B too. And you can't have a static method in that interface with the same name and arguments – fps

3
  • 1
    Because you are trying to override a non-static method with a static one. Which is what the error message is telling you. Commented Sep 23, 2020 at 17:11
  • but why I can override static method? Commented Sep 23, 2020 at 17:13
  • Static methods can not be overridden in the exact sense of the word. It's static Commented Sep 23, 2020 at 17:14

2 Answers 2

2

You cannot override the static method of the interface; you can just access them using the name of the interface. If you try to override a static method of an interface by defining a similar method in the implementing interface, it will be considered as another method.

See this: https://www.tutorialspoint.com/default-method-vs-static-method-in-an-interface-in-java#:~:text=You%20cannot%20override%20the%20static,static)%20method%20of%20the%20class.

Essentially in Java, the keyword static indicates that the particular member belongs to a type itself.

Sign up to request clarification or add additional context in comments.

3 Comments

To add a bit more: You can overload static method.
still not clear, if static methods belong to interface so why B interface can't have static void print() {}
@AdolisPali Becase the default method print is inherited from ABCD, so it's in interface B too. And you can't have a static method in that interface with the same name and arguments
1

Every instance method automatically inherits to their sub classes and only can be overridden by instance method from their sub classes too. Static method can not override instance method. Thus in your case, method "default void print_static()" from ABCD doesn't override "static void print_static()" from B. You still can call ABCD.print_static() for ABCD and print_static() for B.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.