当前位置: 动力学知识库 > 问答 > 编程问答 >

java - What does @Override mean?

问题描述:

public class NaiveAlien extends Alien

{

@Override

public void harvest(){}

}

I was trying to understand my friend's code, and I do not get the syntax, @Override in the code. What does that do and why do we need in coding?

Thanks.

网友答案:

It's a hint for the compiler to let it know that you're overriding the method of a parent class (or interface in Java 6).

If the compiler detects that there IS no function to override, it will warn you (or error).

This is extremely useful to quickly identify typos or API changes. Say you're trying to override your parent class' method harvest() but spell it harvset(), your program will silently call the base class, and without @Override, you wouldn't have any warning about that.

Likewise, if you're using a library, and in version 2 of the library, harvest() has been modified to take an integer parameter, you would no longer override it. Again, @Override would quickly tell you.

网友答案:

This feature is called an annotation. @override is the syntax of using an annotation to let the compiler know, "hey compiler, I am changing what harvest does in the parent class", then the compiler can immediately say, "dude, you are naming it incorrectly". The compiler won't compile until you name it correctly.

So, without this @override annotation, the compiler won't error and it will be considered a new method declaration. It would be difficult to recognize the error at this point.

网友答案:

@Override means you are overriding the base class method. In java6, it also mean you are implementing a method from an interface. It protects you from typos when you think are overriding a method but you mistyped something.

网友答案:

method overriding is Declaring a method in a subclass which is already present in a parent class.

Here's a simple example: Boy class extends Human class. Both classes have a common method void eat(). Boy class is giving its own implementation to the eat() method or in other words it is overriding the method eat().

class Human{
   public void eat()
   {
      System.out.println("Human is eating");
   }
}
class Boy extends Human{
   @override
   public void eat(){
      System.out.println("Boy is eating");
   }
   public static void main( String args[]) {
      Boy obj = new Boy();
      obj.eat();
   }
}

When the compiler sees @override in your code it will automatically call the base class , it's very usefull for detecting typos in case you miss spell your methods.

分享给朋友:
您可能感兴趣的文章:
随机阅读: