As you know the 'program to an interface' design principle broadly prefers supertypes instead of concrete types or implementations.
Is it consistent with the principle to use instanceof in a Java program to derive a concrete type from a supertype?
In my application, Storehouse is an abstract supertype class with a couple of private variables and public getters and setters.
ConcreteStorehouseA inherits from Storehouse and has a lot of concrete methods and variables. ConcreteStorehouseB is similar but different.
My application receives a Storehouse. However, Storehouse is not a useful type to operate on. Because the only really useful methods are contained in the concrete types, I use instanceof as follows:
if (storehouse instanceof ConcreteStorehouseA) {
ConcreteStorehouseA concreteStorehouseA = (ConcreteStorehouseA) storehouse;
// perform operations on the concrete type's useful methods and variables
Is using instanceof compatible with the principle?
Edit:
In essence the application is a dice simulator for a table top RPG, Shadowrun. The concrete types are the different test types - Success Test, Opposed Test, Extended Test - which all have very different factors and parameters for their successful operation. The supertype essentially contains the dice pool!
As a rule of thumb, that "program to interfaces" principle that you mentioned can be translated into: import
only the interface type, don't have any compile-time dependency on subclasses.
Therefore, the answer to your question would be definitely no. You are not programming to interfaces since you cast to concrete types.