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 {
    //定义成员变量时指定默认值,合法
    final int a = 6;
    //下面变量将在构造器或初始化块中分配初始值
    final String str;
    final int c;
    final static double d;

    //既没有指定默认值,又没有在初始化块、构造器中指定初始值
    //下面定义的ch实例是不合法的
    //final char ch;
    //初始化块,可对没有指定默认值的实例变量指定初始值
    {
        //在初始化块中为实例变量指定初始值,合法
        str = "Hello";
        //定义a实例变量时已经指定了默认值
        //不能为a重新赋值,因此下面赋值语句非法
        //a=9;
    }

    //静态初始化块,可对没有指定默认值的类变量指定初始值
    static {
        //在静态初始化块中为类变量指定初始值,合法
        d = 5.6;
    }

    //构造器,可以对既没有指定默认值,又没有在初始化块中,指定初始值的实例变量指定初始值
    public FinalVariableTest() {
        //如果在初始化块中已经对str指定了初始值
        //那么在构造器中不能对final变量重新赋值,下面赋值语句非法
        //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);}
}
Copy after login

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 {
    //定义一个final修饰的实例变量
    //系统不会对final成员变量进行默认初始化
    final int age;
    {
        //age没有初始化,所以此处代码将引起错误,因为它试图访问一个未初始化的变量
        //只要把定义age时的final修饰符去掉,程序就正确了
        System.out.println(age);
        
        age=6;
        System.out.println(age);
    }
    public static void main(String[] args){
        new FinalErrorTest();
    }
}
Copy after login

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){
        //不能对final修饰的形参赋值,下面语句非法
        //a=5;
    }
    public static void mian(String[] args){
        //定义final局部变量时指定默认值,则str变量无法重新赋值
        final String str="hello";
        //下面赋值语句非法
        //str="Java";
        
        //定义final局部变量时没有指定默认值,则d变量可被赋值一次
        final double d;
        d=5.6;
        //对final变量重新赋值,下面语句非法
        //d=6.4;
    }
}
Copy after login

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修饰数组元素,iArr是一个引用变量
final int[] iArr={5,6,12,9};
System.out.println(Arrays.toString(iArr));
//对数组元素进行排序,合法
Arrays.sort(iArr);
System.out.println(Arrays.toString(iArr));
//对数组进行元素赋值,合法
iArr[2]=-8;
System.out.println(Arrays.toString(iArr));
//下面语句对iArr重新赋值,非法
//iArr=null;
Copy after login

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变量引用的字符串可以在编译时就确定下来
//因此s2直接引用变量池中已有的"疯狂Java"字符串
String s2="疯狂"+"Java";
System.out.println(s1==s2);//true

//定义两个字符串直接量
String str1="疯狂";
String str2="Java";
String s3=str1+str2;
System.out.println(s1==s3);//false
Copy after login

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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles