'java interface reference type object can acess other interface memeber in same classe even it not defined inside it?
If I understand this correctly, the reference type determines which member can be accessed (compile time) while the object type determines which member will be used (runtime).
I have class that implements two interfaces. These interfaces are not related (no inheritance relation allowing one to extends member of the other).
One interface when used as reference type of an object can access a method inside the other method.
interface Jump {
// this one do not define anything
}
interface Climb {
default void greeting(){
System.out.println("greeting from Climb interface");
}
}
public class Test implements Jump, Climb {
public Test(){
greeting();
}
public static void main(String[] args) {
Climb climb = new Test(); // this is clear that will call default method in Climb
Jump jump = new Test(); // but why this did compile and print method defined in Jump ?!!!
}
}
The object with reference type Jump interface is assumed to access the member in this interface. And the interfaces are not related. What is going on?
Solution 1:[1]
Why wouldn't this work? It doesn't matter what the variable is defined as; its internal implementation will work the same. You could write
public static void main(String[] args) {
new Test();
}
You don't have to assign it to any variable. There's no typo in that code; it'll work; it'll print greeting from Climb interface.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Louis Wasserman |
