If I have:
public interface One{
public void method1();
}
public interface Two{
public void method2();
}
public class AClass implements One, Two{
}
public static void aDiffMethod1(One o){
o.method1();
}
public static void aDiffMethod2(Two t){
t.method2();
}
public static void main(String[] args){
AClass a = new AClass();
aDiffMethod1(a);
aDiffMethod2(b);
}
Sometimes in my code I will pass an instance of AClass using the fact it is a subtype of the interface One (in other words, the parameter type of the method will be One and I will pass the type AClass) and at other times I may pass the AClass object knowing its a subtype of the interface Two (the parameter type of the method im passing to is Two, so I pass AClass as a subtype of Two).
Is it ok to pass an instance of AClass into different methods under the guise of being a subtype of different interfaces?
Is this what they mean by programming to the interface- so it is fine?
Yes, that is the whole point of interfaces.
Methods that only accept interface
Onewill only ever callmethod1, so this is safe. methods that only accept interfaceTwowill only ever callmethod2, so again, this is safe.