I have seen that if I have interface named interfaceABC.
Example:
public class ABController extends AbstractCOntroller {
private interfaceABC inter;
I am confused that why we make object from interface not from class that implemented it.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
We haven’t created an object/instance yet. We simply declared a variable to hold it. We don’t make objects from interfaces (you have to use a concrete class to do that), but we will often use interface types instead of the actual concrete class for variable declarations, method parameter types, and method return types.
Take this for exmaple:
Using the interface
Listhere instead of the concrete classArrayListfollows a common best practice: to use interfaces instead of concrete classes whenever possible, e.g. in variable declarations, parameters types, and method return types. The reason this is considered a best practice is:Using the interface for declarations and for return types hides an implementation detail, making it easier to modify in the future. For example, we may find that the code works better using a
LinkedListrather thanArrayList. We can easily make this change in one place now, just where the list is instantiated. This practice is especially key for method parameter types and method return types, so that external users of the class won’t see this implementation detail of your class and are free to change it without affecting their code.By using the interface, it may be clearer to a future maintainer that this class needs some kind of
List, but it does not specifically need anArrayList. If this class relied on someArrayList-specific property, i.e. it needs to use anArrayListmethod, than usingArrayList<Example> examples = ...instead ofList<Example> examples = ...may be a hint that this code relies on something specific to anArrayList.It may simplify testing/mocking to use the more abstract
Listthan to use the concrete classArrayList.