[Java] explanation of keywords in Java

Source: Internet
Author: User

Keyword explanation in Java

1. Final

Final keyword modifier member variable

You can define a member variable as final, but such a member variable must be initialized when constructing an object. That is to say, after each constructor is executed, the values of these member variables must be set and cannot be modified in subsequent operations.

For example:

Package COM. dingji. java. test. bean; public class test {final string mname; public test (string name) {// The final variable must be initialized in the constructor; otherwise, the mname cannot be compiled ;}}

What if it is a static final variable? The constructor cannot be initialized. What should I do? We can use static blocks for initialization.

For example:

package com.dingji.java.test.bean;public class Test {static final String mName;static {mName = "dingji";}}

Let's take a look at this piece of code:

Package COM. dingji. java. test. bean; import Java. util. date; public class test {final date mdate; public test () {mdate = new date ();} public void changedate (long milliseconds) {// you can change the mdate object of mdate. settime (milliseconds );}}

We can see from the above that we can change the mdate object, that is, the mdate object cannot be changed, that is, the object reference, and the object can be changed, however, after the object is constructed, mdate points to the object and remains unchanged.

Final keyword modifier class and Method

Sometimes, you may want to prevent people from using a class to define a subclass. classes that cannot be extended are called final classes, if the final modifier is used to define a class, it indicates that the class is a final class.

The methods in the class can also be declared as the final type. If this is done, the subclass will not be able to override this method (all methods in the final class will automatically become the final method ).

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.