安卓@Override的意思 [英] meaning of android @override

查看:232
本文介绍了安卓@Override的意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是完全新的Andr​​oid和想知道在Android上的 @覆盖声明的目的。

I am completely new to android and want to know the purpose of the @Override statement in Android.

推荐答案

@覆盖是的 Java注释。它告诉了下面的方法覆盖它的<一的方法编译href="http://www.java-tips.org/java-se-tips/java.lang/what-is-a-java-superclass.html">superclass.例如,假设你实现一个Person类。

@Override is a Java annotation. It tells the compiler that the following method overrides a method of its superclass. For instance, say you implement a Person class.

public class Person {
   public final String firstName;
   public final String lastName;

   //some methods

   @Override public boolean equals(Object other) {
      ...
   }
}

Person类有一个equals()方法。 equals方法在人的超对象已定义。因此,上述实施平等的()是equals()方法用于人的重新定义。也就是说,人覆盖equals()方法

The person class has an equals() method. The equals method is already defined in Person's superclass Object. Therefore the above implementation of equals() is a redefinition of equals() for Persons. That is to say, Person overrides equals().

这是合法的覆盖方法没有明确标注它。那么,什么是@Override标注好?如果你不小心尝试重载equals()这种方式:

It is legal to override methods without explicitly annotating it. So what is the @Override annotation good for? What if you accidentally tried to override equals() that way:

public boolean equals(Person other) {
   ...
}

以上案件有一个bug。你的意思是重载equals(),但你没有。为什么?因为真正的equals()方法获得一个对象作为参数,你的equals()方法得到一个人作为一个参数。编译器是不会告诉你这个错误,因为编译器不知道你想覆盖。至于编译器可以告诉你实际上意味着以超载 equals()方法。但是,如果你试图等于使用@Override注释覆盖:

The above case has a bug. You meant to override equals() but you didn't. Why? because the real equals() gets an Object as a parameter and your equals() gets a Person as a parameter. The compiler is not going to tell you about the bug because the compiler doesn't know you wanted to override. As far as the compiler can tell, you actually meant to overload equals(). But if you tried to override equals using the @Override annotation:

@Override public boolean equals(Person other) {
   ...
}

现在的编译器知道你有一个错误。你想覆盖,但你没有。因此,要使用@Override注释的原因是显式声明的方法压倒一切的。

Now the compiler knows that you have an error. You wanted to override but you didn't. So the reason to use the @Override annotation is to explicitly declare method overriding.

这篇关于安卓@Override的意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆