I'm having a bit of a hard time grasping the concept of programming to an interface and using abstract classes at the same time.
I have a set of "Retriever" classes which retrieve different types of data from the Internet. These retriever classes retrieve strings of JSON responses
public class AccountRetriever extends DataRetriever implements AccountInformation{
List<String> getAccountInformation{
....
}
}
public class BalanceRetriever extends DataRetriever implements BalanceInformation{
List<String> getBalanceInformation{
....
}
}
Both AccountInformation and BalanceInformation are interfaces with the methods shown in them. I am also extending from an abstract class "DataRetriever" which has a method called
public String getResponseAsString();
After instantiating these classes in my main using interfaces:
AccountInformation ai = new AccountRetriever(apiRequest);
List<String> aiList = ai.getAccountInformation(); <----this works
ai.getResponseAsString(); <----this doesn't work. Why??
BalanceInformation bi = new BalanceRetriever(apiRequest);
List<String> biList = bi.getBalanceInformation(); <----this works
bi.getResponseAsString(); <----this doesn't work. Why??
The getResponseAsString() method exists in the abstract class each of these retrievers extend from so why am I unable to access that method? The only methods that I can access are the ones in the interface. What am I doing wrong here?
These methods aren't visbale because while you construct a AccountRetriever
, your ai
variable is only of type AccountInformation
, the interface which only has getAccountInformation()
not getResponseAsString()
AccountInformation ai = new AccountRetriever(apiRequest);
List<String> aiList = ai.getAccountInformation(); <----this works
ai.getResponseAsString(); <----this doesn't work. Why??
But if you change the variable type to DataRetriever
then getAccountInformation()
will be visible but getAccountInformation()
will not.
DataRetriever ai = new AccountRetriever(apiRequest);
List<String> aiList = ai.getAccountInformation(); <----this wont work
ai.getResponseAsString(); <---- this will work
You will need to change the variable type to AccountRetriever
which both extends DataRetriever
and implements AccountInformation
AccountRetriever ai = new AccountRetriever(apiRequest);
List<String> aiList = ai.getAccountInformation(); <----this will work
ai.getResponseAsString(); <---- this will work
Or, change your design so that both AccountInformation
and BalanceInformation
both extends a common interface which defines getResponseAsString()
. And remove the abstract class all together.
public interface Information {
public String getResponseAsString();
}
public interface AccountInformation extends Information {
public List<String> getAccountInformation();
}
public interface BalanceInformation extends Information {
public List<String> getBalanceInformation();
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments