Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

java - 什么时候使用Java的@Override注释,为什么?(When do you use Java's @Override annotation and why?)

What are the best practices for using Java's @Override annotation and why?

(使用Java的@Override注释的最佳实践是什么,为什么?)

It seems like it would be overkill to mark every single overridden method with the @Override annotation.

(用@Override注释标记每个被覆盖的方法似乎是多余的。)

Are there certain programming situations that call for using the @Override and others that should never use the @Override ?

(是否有某些编程情况要求使用@Override而另一些则永远不要使用@Override ?)

  ask by Alex B translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use it every time you override a method for two benefits.

(每次您重写一种方法都有两个好处时使用它。)

Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are.

(这样做是为了使您能够利用编译器检查的优势,以确保您认为自己确实覆盖了某个方法。)

This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does.

(这样,如果您犯了拼写错误的方法名称或不正确匹配参数的常见错误,将会警告您方法实际上并没有像您认为的那样覆盖。)

Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.

(其次,它使您的代码更易于理解,因为当方法被覆盖时,它更加明显。)

Additionally, in Java 1.6 you can use it to mark when a method implements an interface for the same benefits.

(另外,在Java 1.6中,您可以使用它来标记方法何时实现接口以实现相同的好处。)

I think it would be better to have a separate annotation (like @Implements ), but it's better than nothing.

(我认为最好有一个单独的注释(例如@Implements ),但总比没有好。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...