Java interface methods never used

半城伤御伤魂 提交于 2021-02-18 18:14:12

问题


So, I started using interfaces in Java a while ago. I have already created one, and I have a class, that implements that interface.

So this is the interface itself:

And this is the class that implements the Actor interface:

But, as you can see in the first picture, no methods are used, ecxept for create(). The most strange thing is that everything works absolutely fine! Only these underlined words freak me out a bit)


回答1:


Your methods are never actually used. This is IntelliJ's way of highlighting dead code. Until you actually instantiate an Actor and call the method (see code sample below), it will appear as unused.

Actor actor = new Balls();
actor.createBody();



回答2:


There is nothing wrong with these warnings: the IDE tells you that you could delete the underlined methods from the interface, because there is no code in your solution that would call these methods through the specific interface.

In top-down development, most interfaces start off looking like this: you start with an interface that has a lot of methods that nobody calls, and then the number of the unused methods goes down as you start using other operations from the interface. Eventually the number of unused methods goes down to zero, because your code starts making use of all interface methods that you define (or you delete the unused methods from your interface).




回答3:


By default all methods in interface are abstract. That means they cannot have any definition. If everything runs and you have underlines, these are probably warnings. You can view more information by placing your cursor on underlined text (happens in Eclipse IDE). When you implement the interface you have to override all the methods present in interface, which you have done otherwise you would have got compile time error.

You have actually implemented/ used all methods of interface. Notice the curly brackets after method definitions in your class Balls. You just haven't written any code in them.

Read more about interfaces and you'll get a clearer picture.



来源:https://stackoverflow.com/questions/28727594/java-interface-methods-never-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!