if we cast an object to an interface, won\'t this object be able to call its own methods? in the following example, myObj
will only be able to call MyInterface meth
MyInterface myObj = new Obj();
MyInterface mySec = new Sec();
You declare an instance of a MyInterface named myObj. You initialize it with new Obj(); which is authorized by the compiler if Obj implements MyInterface. myObj can only call MyInterface methods obviously. Same for the second line.
Here is a sample code to try:
public class Test {
public static void main(String args[]){
A a = new A();
a.say();
a.a();
B b = new B();
b.say();
b.b();
I ia = new A();
ia.say();
ia.a(); // fail
}
}
interface i {
public void say();
}
class A implements i {
public void say(){
System.out.println("class A");
}
public void a(){
System.out.println("method a");
}
}
class B implements i {
public void say(){
System.out.println("class B");
}
public void b(){
System.out.println("method b");
}
}