Please read full question, Its different from this type of question Difference between interface and class objects
Example: 1
Class implementing Interface
public interface a{
void foo();
}
public class b implements a{
@Override
void foo(){}
void bar(){}
}
Working behaviour
a asd=new b(); can call only foo()
b asf=new b(); can call both foo() and bar()
I hope upto here its clear.
Example 2:
Now there is one class CheckingPhase
and IdentifyCheckingPhase
class IdentifyCheckingPhase {
private static a getPhase() {
return a;
}
private static void matchPhase(){
(CheckingPhase)IdentifyCheckingPhase.getPhase().bar();
}
}
class CheckingPhase implements a {
@Override
void foo() {
}
void bar(){
}
}
In Example 1
. Interface instance only able to call its own implemented method in class and class instance able to all methods (class itself and Interface too). If that's a case, am sure something different being maintanied in compiler side that's why its able to differentiate.
Doubt First, Its correct to say that Interface and Class ref always points to different types instances of same class ? I guess yes, that's they are able to call their own methods. (Interface only its own methods but class ref can call all)
If not, Then In second example, a
returned from getPhase()
, should not be allowed to replace with CheckingPhase
in matchPhase()
and call its class instance method. Because a
allowed to call only foo
and CheckingPhase
can call foo and bar
both.
Doubt 2, I'm wondering, Is it syntactically correct using CheckingPhase
instead of a
while coming from method getPhase()
to matchPhase()
?
I hope its clear what am trying to ask. Please let me know if may qyestion is not clear. (Its more about how java is using Syntax for above use case)