Вопрос

I know that in Java is tag @Override to annotate method which overrides method from superclass, if not there is a warning. My question: is there an opposite tag to annotate method which we do not want to override method from superclass (eg. by accident)?

I know that I can set method in superclass final, but this solution involves changes in superclass code. That's what I don't want to do - just want to change my code :)

I know that I can set another name for this method, but sometimes in super class there is a lot of methods and you simply not aware of them. So when you implement your own in subclass you might by accident use the same name. How to avoid this?

Это было полезно?

Решение

No, there is no pre-defined Java annotation that is the inverse of @Override.

Having said that, most IDE's should be able to identify if a method is overriding another. For instance Eclipse has this feature. If you look at your class in Outline view, you'll see a small triangle where overrides occur. For example:

enter image description here

I have to believe that NetBeans and IntelliJ Idea must have similar functionality.


As an aside, this problem that you're trying to address, that of avoiding inadvertently overriding a parent method, is a serious and pernicious one, one that has an especially elevated risk when extending classes that have many methods or a large inheritance hierarchy (think Swing components as an example -- I once had a majorly frustrating GUI bug due to my tripping over accidentally overriding JPanel's getX() and getY() methods). This is another reason to in general prefer composition over inheritance if composition makes sense in the situation.

Другие советы

I've been getting this warning in NetBeans even though I was not in fact overriding the method. I was just invoking a subclass method from within the subclass constructor and NetBeans was flagging this as an override.

Even though there is no inverse @override tag, a simple solution is to just make the method private instead of public/protected if you know you won't be overriding it or using it anywhere below the subclass that it's in.

Give the method in the sub-class a different name or signature than the method in the super-class that you wish to not override.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top