Hide the base object.
Say you have:
public interface A { } public class B implements A { }
Thus, interface A implements only a subset of the functionality of B. Effectively, it hides parts of B. Your question is how to stop the user from lowering A to B.
B objectOfTypeB = (B)objectOfTypeA;
So, do not give the user access to class B. If the user cannot import it, he cannot create an instance or refuse it. Thus, it forces you to use the interface and nothing more.
Change the above code to:
public interface A { } public class B implements A { }
Then you can simply return function A, protected by the fact that the user cannot use B.
public A foo() { return objectOfTypeB; }
source share