Static and non-static methods with the same name in the parent class and implementation interface

Don't ask about the difference between an interface and an abstract class.

Success works successfully, right?

interface Inter { public void fun(); } abstract class Am { public static void fun() { System.out.println("Abc"); } } public class Ov extends Am implements Inter { public static void main(String[] args) { Am.fun(); } } 

Why is there a conflict?

+6
source share
2 answers

A static and non- static method cannot have the same name in the same class . This is because you can access the static and non static methods using the link, and the compiler will not be able to decide whether you want to call the static method or the static method.

Consider the following code, for example:

 Ov ov = new Ov(); ov.fun(); //compiler doesn't know whether to call the static or the non static fun method. 

The reason Java can allow the static method to be invoked using a reference allows developers to easily change the static method to the non static method.

+7
source

We must write our code so that it is syntactically correct. It is also equally important to understand that our code does not create any ambiguity for the compiler. If we have such ambiguity, the language developers took care not to allow the compilation of such code.

A class inherits the behavior of its superclass. Access to static methods can be obtained simply from the class name, as well as from the instance. Suppose that there is a method with the same name and signature (except for the static ), calling the method in the instance will leave the compiler to throw. How will he decide what the programmer intends to do, which of the two methods does he intend to call? Therefore, the language developers decided that this case would lead to a compilation error.

According to

http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.8.2

If class C declares or inherits the static method m, then it is said that m hides any method m ', where signature m is the submission (§8.4.2) of signature m' in superclasses and superinterfaces C that would otherwise be available for code in C. This is a compile-time error if the static method hides the instance method.

 public class Ov extends Am implements Inter { public static void main(String[] args) { Ov.fun(); //static method is intended to call, fun is allowed to be invoked from sub class. Ov obj = new Ov(); obj.fun(); //** now this is ambiguity, static method can //be invoked using an instance, but as there is //an instance method also hence this line is ambiguous and hence this scenario results in compile time error.** } } 
+2
source

Source: https://habr.com/ru/post/1014913/


All Articles