[Code optimization] Stick to the override Annotation

Source: Internet
Author: User

For traditional programmers, the most important thing in the annotation is the override annotation. The annotations here refer to declarations that can only be used in methods,

She indicates that the annotated method is used to overwrite a declaration of the parent class. If you stick to this annotation, it can prevent illegal errors of a major category.

<span style="font-size:14px;">public class Bigram{private final char first;private final char second;public Bigram (char first ,char second){this.first=first;this.second=second;}public boolean equals(Bigram b){return b.first==first && b.second==second;}public int hashCode(){return 31*first+second;}public static void main (String args[]){.....s.add(new Bigram(ch,ch));}}</span>


This Code does not get the expected result because the bigram class creator originally wanted to overwrite the equals method and overwrite the hashcode method at the same time.

However, it is unfortunate that the equals method is overloaded. (The equals method must be passed into the object class.) This equals method tests the object's identity, just like =

The operators are the same. This is why you cannot get the desired result.


If we add override to reload the parent class method identifier when writing code, this type of error can be avoided.


In today's ide, the override annotation check function is provided, which enables you to find this method problematic during compilation.

<span style="font-size:14px;">public boolean equals(Bigram b){return b.first==first && b.second==second;}</span>


In short, remember to use the override annotation, the compiler will help you prevent a large number of errors, but there is an exception. Note not necessary in the detail class

Are you sure you want to override the abstract method declaration method.

[code optimization] Stick to the override annotation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.