Adolis Pali
Adolis Pali

Reputation: 339

Java interfaces override method

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

Upvotes: 0

Views: 72

Answers (2)

Ferry
Ferry

Reputation: 414

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.

Upvotes: 1

Kuldeep Jain
Kuldeep Jain

Reputation: 8598

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.

Upvotes: 2

Related Questions