Interfaces | Sololearn: Learn to code for FREE!



Why should I create interfaces in java? Can I describe functions of interface in one class and then use them just by implementing the Interface and call them or I should describe function in every class I implementing the Interface? As i know KeyListener is an Interface. How can I make something similar to KeyListener with interfaces functions that are called automatically?

8/9/2019 5:02:07 PM


4 Answers

New Answer


Lighton Extending your own interface from AbstractEventLister or implementing AbstractEventLister in your class should work, you can use callback mechanism, or message passing between threads, MVC or Command design pattern


Lighton interfaces are abstraction of contracts/protocol that says any class that implements the interface exhibit a certain specific behavior, honors the protocol by implementing the methods of the interface and thus essentially is an interface or subtype All classes that implement an interface must provide definition of all method of the interface, failing to do so make the class abstract and hence cannot be instantiated. The easiest way to make an interface like KeyListener is to extended your interface from KeyListener and customize it in implementing class. Writing interfaces is not necessary, but then you may have many classes that needs to fulfill specific protocols in their own way, so it's better to extract core functionality. But lasses too do the same, so why interface. The reason classes have limitation as they allow single inheritence, moreover the deriving classes may node need inherited functionality , they only need to exhibit/satisfyv certain contract. Also classes can implement multiple interfaces allowing them to satisfy multiple contract at a time.


Like KeyListener I mean to be called automatically when something happens. For example when something is moved then check for collision or something like that!


This question requests lines in order, but the main class calls lines in wrong order. Is this intentional (so we find the error to pass) or is there something I'm missing to make the lines come out in right order without changing the main class?