Answer the question
In order to leave comments, you need to log in
Why place a reference to an object with an implementation of an interface in a variable of the type of this interface?
Hello!
To solve one problem, I was shown some code that used collections. I began to read about them, formed a general picture, but some points remained unclear.
The HashSet class is, after all, an implementation of the Set interface, i.e. it contains implementations of the methods contained in the Set interface. (do I understand this correctly?)
Why do we create an interface type variable so that it refers to an object whose class implements this same interface?
Why we can't and shouldn't write simply I
've already read a lot about collections, watched video tutorials, but still everything is in a fog. final Set<KeyCode> codes = new HashSet<>();
final HashSet<KeyCode> codes = new HashSet<>();
Answer the question
In order to leave comments, you need to log in
In order to pass not a concrete class, but an interface. Then we will not depend on the specific implementation of the interface. In principle, if inside the method we use only the implementation of the class, then the interface can not be pulled.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question