J2SE synthesis: A little understanding of final

Source: Internet
Author: User
Tags final

In the process of programming, we always encounter the final keyword, then we have to final how to understand, the following is a little superficial understanding of me, and you share.

package zy.pro.jbd.demo;
public class FinalDemo {
final  int  numInt1=16;
final String str="zy";
final String str1;

Note: STR1 is not initialized here, you must initialize it in the constructor, or you will have to make an error. In other words, the final variable must be initialized.

public FinalDemo() {
str1="zy";
}
public static void main(String[] args){
System.out.println("-------------------------------------------------");
}
public void executeFinalTest(){
}
private void testFinalInt(){
numInt1+=1;

Above, we define NUMINT1 as final variable, and an error will occur at the time: cannot assign a final value to final variable numInt1 in line 24

Thus, if a variable of a basic type is defined as final, then this variable will no longer be changed.

System.out.println(numInt1);
}
private void testFinalString(){
str=str+"aaaaa";

The same error is also shown here.

System.out.println(str);
}
}

Let's make one more test:

(1) First create a class: A.java

package zy.pro.jbd.testbase;
public class A {
int t=10;
public A() {
}
public void setT(int t){
this.t=t;
}
public int getT(){
return this.t;
}
}
(2) write the following test code

final A a = new A();
public void testFinalObject() {
a.setT(29);
System.out.println("t:   " + a.getT());
}

The results of the test output are:

T:29

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.