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
Only the methods in the interface are visible, but all methods in the object may still be invoked, as long as they're made accessible otherwise. For example:
public interface MyInterface {
String getName();
}
public class Obj implements MyInterface {
private String getFirstName() {
return "John";
}
private String getLastName() {
return "Doe";
}
@Override
public String getName() {
return getFirstName() + " " + getLastName();
}
}
public class Sec implements MyInterface {
private String getDate() {
return new Date().toString();
}
@Override
public String getName() {
return getDate();
}
}
In the above cases, both Obj
and Sec
can call their private members, even though they will not be visible in other classes. So when you say...
MyInterface myObj = new Obj();
MyInterface mySec = new Sec();
...as you've asked in the question, while it is true that in myObj
and mySec
the only method visible is getName()
, their underlying implementation can be different.