What is @Override for in Java? [duplicate]

人走茶凉 提交于 2019-11-28 16:57:53

问题


Possible Duplicate:
When do you use Java’s @Override annotation and why?

Is there any reason to annotate a method with @Override other than to have the compiler check that the superclass has that method?


回答1:


As you describe, @Override creates a compile-time check that a method is being overridden. This is very useful to make sure you do not have a silly signature issue when trying to override.

For example, I have seen the following error:

public class Foo {
  private String id;
  public boolean equals(Foo f) { return id.equals(f.id);}
}

This class compiles as written, but adding the @Override tag to the equals method will cause a compilation error as it does not override the equals method on Object. This is a simple error, but it can escape the eye of even a seasoned developer




回答2:


It not only makes the compiler check - although that would be enough to make it useful; it also documents the developer's intention.

For instance, if you override a method but don't use it anywhere from the type itself, someone coming to the code later may wonder why on earth it's there. The annotation explains its purpose.




回答3:


Nope, you pretty much nailed it.

@Override tells the compiler your intent: if you tag a method @Override, you intended to override something from the superclass (or interface, in Java 6). A good IDE will helpfully flag any method that overrides a method without @Override, so the combination of the two will help ensure that you're doing what you're trying to.




回答4:


nope -- except that it also improves readability (i.e. in addition to whatever indicator your IDE uses, it makes it easy to spot that a method overrides a declaration in the superclass)



来源:https://stackoverflow.com/questions/561365/what-is-override-for-in-java

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