How do interfaces in Java get an Object class method?

I know that in the case of dynamic binding, you can call only those methods that are present in the current class. If the child overrides the parent method, then the child method is executed, otherwise the parent method will be executed ...

But in the case of interfaces, what happens, I don’t know ... Here is an example of what I mean:

interface TestInterface { public void show(); } class Test implements TestInterface { public void show() { System.out.println("Hello in show"); } public String toString() { System.out.println("Hello in To String"); return ""; } public static void main(String[] args) { TestInterface obj = new Test(); obj.show(); obj.toString(); // why it run vilate dynamic binding rule.. } } 
+4
source share
4 answers

In the case of interfaces in java: - "All interfaces get the entire open and abstract method of the Object class"

+1
source

This is because interfaces implicitly include all public methods declared in Object .

This is indicated in the JLS section, 9.2 Member .

9.2 Interface members

[...]

  • If the interface does not have direct superinterfaces, then the interface implicitly declares a public method of abstract members m with signature s returned by type r and a throws clause corresponding to each method of a public instance m with signature s, the return type is r, and the sentence th> t declared in Object , if only a method with the same signature, the same type of return value and the offer of a compatible throw is explicitly declared by the interface.

[...]

+11
source

Because in the case of interfaces, it implicitly includes all public methods declared in Object

+1
source

Your code does not compile. I changed your code to:

 interface TestInterface { public void show(); } class Test implements TestInterface { @Override public void show() { System.out.println("Hello in show"); } @Override public String toString() { return "Hello in To String"; } public static void main(String[] args) { TestInterface obj = new Test(); obj.show(); System.out.println(obj.toString()); } } 

Result:

 Hello in show Hello in To String 
0
source

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


All Articles