亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Java Javagetting Started java object-oriented final modifier

java object-oriented final modifier

Nov 26, 2019 pm 02:43 PM
final java modifier object-oriented

java object-oriented final modifier

1. Final modifier definition:

The final keyword can be used to modify classes, variables and methods

final modification When a variable is used, it means that the variable cannot be changed once it obtains the initial value (strictly speaking: a variable modified by final cannot be changed. Once the initial value is obtained, the value of the final variable cannot be reassigned)

final can modify not only member variables (class variables and instance variables), but also local variables and formal parameters

Related video learning tutorials:java online learning

2. Final member variable syntax stipulates:

Final modified member variables must have an initial value explicitly specified by the programmer, and the system will not implicitly initialize final members.

1. The places where final-modified class variables and instance variables can set initial values ??are as follows:

Class variables: The initial value must be specified in the static initialization block or when declaring the class variable. value, and an

instance variable must be specified in only one of two places: the initial value must be specified in a non-static initialization block, in a declaration of the instance variable, or in a constructor, and only in three places One of them is specified

Note: If the normal initialization block has specified an initial value for an instance variable, you can no longer specify an initial value for the instance variable in the constructor

The following program demonstrates the effect of final modified member variables:

package lextends;
public class FinalVariableTest {
    //定義成員變量時(shí)指定默認(rèn)值,合法
    final int a = 6;
    //下面變量將在構(gòu)造器或初始化塊中分配初始值
    final String str;
    final int c;
    final static double d;

    //既沒(méi)有指定默認(rèn)值,又沒(méi)有在初始化塊、構(gòu)造器中指定初始值
    //下面定義的ch實(shí)例是不合法的
    //final char ch;
    //初始化塊,可對(duì)沒(méi)有指定默認(rèn)值的實(shí)例變量指定初始值
    {
        //在初始化塊中為實(shí)例變量指定初始值,合法
        str = "Hello";
        //定義a實(shí)例變量時(shí)已經(jīng)指定了默認(rèn)值
        //不能為a重新賦值,因此下面賦值語(yǔ)句非法
        //a=9;
    }

    //靜態(tài)初始化塊,可對(duì)沒(méi)有指定默認(rèn)值的類變量指定初始值
    static {
        //在靜態(tài)初始化塊中為類變量指定初始值,合法
        d = 5.6;
    }

    //構(gòu)造器,可以對(duì)既沒(méi)有指定默認(rèn)值,又沒(méi)有在初始化塊中,指定初始值的實(shí)例變量指定初始值
    public FinalVariableTest() {
        //如果在初始化塊中已經(jīng)對(duì)str指定了初始值
        //那么在構(gòu)造器中不能對(duì)final變量重新賦值,下面賦值語(yǔ)句非法
        //str="java"
        c = 5;
    }

    public void changeFinal() {
        //普通方法不能為final修飾的成員變量賦值
        //d=1.2
        //不能在普通方法中為final成員變量指定初始值
        //ch = 'a';
    }
public static void mian(String[] args){
    FinalVariableTest ft= new FinalVariableTest();
    System.out.println(ft.a);
    System.out.println(ft.c);
    System.out.println(ft.d);}
}

2. If you plan to initialize final member variables in the constructor or initialization block, do not access the value of the member variable before initialization.

package lextends;
public class FinalErrorTest {
    //定義一個(gè)final修飾的實(shí)例變量
    //系統(tǒng)不會(huì)對(duì)final成員變量進(jìn)行默認(rèn)初始化
    final int age;
    {
        //age沒(méi)有初始化,所以此處代碼將引起錯(cuò)誤,因?yàn)樗噲D訪問(wèn)一個(gè)未初始化的變量
        //只要把定義age時(shí)的final修飾符去掉,程序就正確了
        System.out.println(age);
        
        age=6;
        System.out.println(age);
    }
    public static void main(String[] args){
        new FinalErrorTest();
    }
}

3. Final local variables

1. Definition: The system will not initialize local variables, and local variables must be explicitly initialized by the programmer. Therefore, when using final to modify local variables, you can specify a default value when defining it, or you can not specify a default value.

The following program demonstrates the final modification of local variables and formal parameters:

(The case of final modified formal parameters, because when this method is called, the system completes the initialization based on the parameters passed in. Therefore, values ??cannot be assigned using the final modifier.)

package lextends;
public class FinalLocalVariable {
    public void test(final int a){
        //不能對(duì)final修飾的形參賦值,下面語(yǔ)句非法
        //a=5;
    }
    public static void mian(String[] args){
        //定義final局部變量時(shí)指定默認(rèn)值,則str變量無(wú)法重新賦值
        final String str="hello";
        //下面賦值語(yǔ)句非法
        //str="Java";
        
        //定義final局部變量時(shí)沒(méi)有指定默認(rèn)值,則d變量可被賦值一次
        final double d;
        d=5.6;
        //對(duì)final變量重新賦值,下面語(yǔ)句非法
        //d=6.4;
    }
}

4. The difference between final modified basic type variables and reference type variables

Reference type variables that use final modification cannot Being reassigned, but the content of the object referenced by the reference type variable can be changed

For example, the array object referenced by the iArr variable below, the iArr variable after final modification cannot be reassigned, but the array of the array referenced by iArr Elements can be changed

eg.
//final修飾數(shù)組元素,iArr是一個(gè)引用變量
final int[] iArr={5,6,12,9};
System.out.println(Arrays.toString(iArr));
//對(duì)數(shù)組元素進(jìn)行排序,合法
Arrays.sort(iArr);
System.out.println(Arrays.toString(iArr));
//對(duì)數(shù)組進(jìn)行元素賦值,合法
iArr[2]=-8;
System.out.println(Arrays.toString(iArr));
//下面語(yǔ)句對(duì)iArr重新賦值,非法
//iArr=null;

5. Final variables that can execute "macro replacement"

1. For a final variable, whether it is a class variable or instance Variable, or local variable, as long as the variable meets three conditions, this final variable is no longer a variable, but equivalent to a direct quantity.

(1) Use the final modifier to modify

(2) Specify the initial value when defining the final variable

(3) The initial value can be set at compile time Determined

2. An important use of the final modifier is to define "macro variables". When a final variable is defined, an initial value is assigned to the variable, and the variable can be determined when it is a variable. Then this final variable is essentially a "macro variable", and the compiler will delete all variables that use this variable in the program. place directly replaced by the value of the variable.

3,

eg.
String s1="瘋狂Java";
//s2變量引用的字符串可以在編譯時(shí)就確定下來(lái)
//因此s2直接引用變量池中已有的"瘋狂Java"字符串
String s2="瘋狂"+"Java";
System.out.println(s1==s2);//true

//定義兩個(gè)字符串直接量
String str1="瘋狂";
String str2="Java";
String s3=str1+str2;
System.out.println(s1==s3);//false

For s3, its value is obtained by concatenating str1 and str2. Since str1 and str2 are just two ordinary variables, the compiler will not execute the "macro" Replace ", so the compiler can't determine the value of s3 and can't make s3 point to "Crazy Java" cached in the string pool.

For more java related articles and tutorials, you can visit: java introductory tutorial

The above is the detailed content of java object-oriented final modifier. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Google Chrome cannot open local files Google Chrome cannot open local files Aug 01, 2025 am 05:24 AM

ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

See all articles