Final class of Java

Source: Internet
Author: User
Tags final inheritance

If the entire class is final (prefixed with the final keyword before its definition), it means that you do not want to inherit from this class, or that no one else is allowed to take this action. In other words, for this or that reason, our class certainly does not need to make any changes, or for security reasons, we do not want subclasses (subclass processing).
In addition to this, we may also take into account the efficiency of implementation and want to ensure that all actions involving such objects are as effective as possible. As shown below:

: Jurassic.java
//making an entire class final

class Smallbrain {}

final class dinosaur {
  int i = 7;
  int j = 1;
  Smallbrain x = new Smallbrain ();
  void F () {}
}

//! class further extends dinosaur {}
//Error:cannot Extend final class ' dinosaur '

publ IC class Jurassic {public
  static void Main (string[] args) {
    dinosaur n = new Dinosaur ();
    N.F ();
    N.I = n;
    n.j++
  }
} ///:~

Note that data members can be either final or not, depending on our specific choice. The rules applied to final are also applicable to data members, regardless of whether the class is defined as final. When you define a class as final, the result is just a ban on inheritance-no more restrictions. However, because it prohibits inheritance, all methods in a final class are defaulted to final. Because they cannot be overwritten at this time. So the compiler now has the same efficiency choice as we explicitly declare a method final.
You can add a final indicator to a method within the final class, but that doesn't make any sense.

Related Article

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.