Implement an interface and override methods in Java?

后端 未结 6 1020
旧巷少年郎
旧巷少年郎 2021-01-24 16:14

Why do you have to override all methods of an interface?

For instance if I have

public class Foo extend JFrame implements ActionListener, KeyListener {
          


        
6条回答
  •  Happy的楠姐
    2021-01-24 16:18

    If you implement an interface, that means that the implemented object can be used in any scenario where a implementation is expected. From that point of view is quite obvious that you must implement all methods of an interface, otherwise you cannot really say that you have implemented it. e.g. if I have a ICalculator interface with a Add and Subtract method, and you want only to implement Add, could the resulting class really be used by another project that needs a ICalculator?

    However, I quite understand your ire about implementing some of the interfaces in the frameworks today, as they clearly break the Interface Segragation Principle. What that means is that some interfaces are clumps of several functionalities that can be used together to do something useful. E.g. if the ICalculator inteface, instead of just basic Add, Divide etc.. methods, I started adding methods like StandardDeviation that are not essential to the nature of the Calculator object.

    Bottom line, yes, you have to implement each and every one of the interface's members, however, If you are sure and know that some of them will never be used, feel free to leave them empty, or even better, make them throw exceptions, so you'll be sure that never really means never.

提交回复
热议问题