Java study notes 18 --- final keywords modify variables, methods, and classes, study notes 18 --- final

Source: Internet
Author: User

Java study notes 18 --- final keywords modify variables, methods, and classes, study notes 18 --- final

The word final in English is known as "final". In fact, it also means"Unchangeable". In Java,The final keyword is "unchangeable" to better explainThat is, the final modifier is "unchangeable ". Final can modify variables, member methods, and classes, and also the parameters of methods, but the parameters are variables in the final analysis. The following is a detailed explanation.


Author: Chan

Please respect the author's Labor achievements. for reprinting, please mark "reprinted" in the title and the original article link:

Http://www.cnblogs.com/chanchan/p/7936388.html

 

1. final can modify member variables and local variables

(1 ).Final modifiedThe value of a variable cannot be changed., Even if the new value is the same as the old value.

For example:

Final int I = 1; // defines the int type variable I and assigns the initial value 1

// I = 2; // wrong

// I = 1; // wrong

Neither of the commented rows can be found."The final local variable I can not be assigned. It must be blank and not using a compound assignment .".

(2 ).Final modified member variables and local variables must be assigned a value before use.

1 ).For member variables, initial values can be assigned directly during definition;

2 ).You can also define not assigning an initial value before assigning values to it in the constructor.

That is to say, after an object is created, the final member variable of the object must be assigned with the initial value. It does not matter if the final member variable of the object is assigned earlier (when defined) or later (assigned in the constructor.

Note: In the second case, if multiple constructor methods exist, each constructor must have an assignment statement, otherwise, The "The blank final field height may not have been initialized..

3 ).If the static member variable is modified to final, the variable can be regarded as a global variable, that is, the value of the variable is unchangeable throughout the loading of the class.

For example:

Static final String citizenship = "Chinese ";

Citizenship is both static and final. static indicates that it belongs to the entire class, and memory is allocated when the class is loaded (seeNote 9), Final indicates that the value is immutable, that is, the fixed position content is also fixed.

(3 ).Divides Member variables and local variables from the variable type,

1 ).When the variable is of the basic data type, the value of the variable cannot be changed;

2 ).When a variable is of reference type, the value of the variable itself cannot be changed, that is, the variable cannot point to another object or array;

HoweverThe content of the object or array to which the variable points can be changed.;

For example:

Final Person per = new Person (); // defines a Person Class Object Reference per and points to the new object

// Per = new Person (); // re-create a Person Class Object and point the object to it by the same error as above, that is, the reference type variable modified by final cannot be re-assigned.

Per. name = "me"; // the content of the object to which per points can be changed

 

For ease of understanding, see the following memory diagram:

 

2. final can modify member Methods

(1 ).The final modified member method cannot be overwritten by the quilt class, that is, when the parent class method is final, the sub-class cannot have the same method as the parent class in terms of method name, parameter type, number of parameters, and Parameter order, except when the parent class is private,For details, see the following section (3)But the subclass can call the final method of the parent class.

See the following code:

Method of the Person class: final void finalMethod () {int I = 2; System. out. println ("finalMethod: I =" + I);} is called by the Student class Object Reference in TestMain: public class TestMain {public static void main (String [] args) {Student stu = new Student (); stu. finalMethod ();}

Output result: finalMethod: I = 2

(2 ).The default access permission for a private method is final, but the subclass cannot call the private method. For details about the access permission modifier, seeNote 10.

(3 ).When a method of the parent class is private final and the member method of the subclass has the same name as the member method of the parent class but is only modified by final, isn't it overwritten?

Method of the Person class: private final void priFinalMethod () {System. out. println ("Person: priFinalMethod");} Student class method: final void priFinalMethod () {System. out. println ("Student: priFinalMethod");} TestMain class: package human; public class TestMain {public static void main (String [] args) {Person per = new Person (); student stu = new Student (); Person per1 = stu; // per. priFinalMethod (); stu. priFinalMethod (); // per1.priFinalMethod ();} main method of the Person class: public static void main (String [] args) {Person per = new Person (); student stu = new Student (); Person per1 = stu; per. priFinalMethod (); stu. priFinalMethod (); per1.priFinalMethod ();}

The output of the TestMain class is:

Student: priFinalMethod

1 ).The two lines commented out in the TestMain class indicate that the method is invisible;

2 ).For per, the private method is visible only to this class and invisible in the TestMain class, so per cannot call the priFinalMethod;

3 ).For per1, per1 is a reference to the Student object. per1 can only call the methods that have been rewritten in Student and the methods in the Person class. As this still prompts that this method is invisible, combined with 2) yes,The priFinalMethod method is not overwritten by the quilt class.Otherwise, you can call it;

 

The output of the Person class is:

Person: priFinalMethod
Student: priFinalMethod
Person: priFinalMethod

The first two lines are easy to understand. The last line,Per1 calls priFinalMethod in the Person class, which further indicates that this method has not been overwritten by the subclass;

Otherwise, the priFinalMethod method of the subclass is called first.

 

3. final can modify the parameters of member methods.

The parameters of the member method modified by final cannot be changed. In fact, the parameters are variables.See 1You can.

The concept of participation in real parameters is also involved here.

 

4. The final class can be modified.

Classes modified by final cannot be inherited by the quilt class, and their member methods are also final by default,But the member variables can be changed.See the following code:

package human;public final class FinalClass {    int i = 1;        void test() {        System.out.println("FinalClass:test");    }        public static void main( String[] args ) {        FinalClass ficl = new FinalClass();                System.out.println("ficl.i = " + ficl.i);        ficl.i = 2;        System.out.println("ficl.i = " + ficl.i);    }}

Output result:

Ficl. I = 1
Ficl. I = 2

You can modify the I value.

 

Attached test source code:

Person class:

Package human; public class Person {// class Person {String name; int age; String gender; // note 18: final modifier member variable, and when the member variables are class references, final int height = 160; // final int height; final EduBackground edu = new EduBackground (); public Person () {// final height = 160;} // note 18: when final is used to modify local variables, modify member methods, and modify parameters of local variables, the value of the local variable cannot be changed to void finalLocal () {// final int I = 1; final int I; // I = 3; final EduBackground edu = new EduBackground (); // edu = new EduBackground (); I = 1; System. out. println ("finalLocal: I =" + I);} // when modifying a method parameter, the parameter cannot be modified by void finalArgs (final int I) {/I = 3; system. out. println ("finalArgs: I =" + I);} void finalArgs (final EduBackground edu) {// edu = new EduBackground (); System. out. println ("finalArgs: edu");} // when modifying a member method, the member method cannot overwrite final void finalMethod () {int I = 2; System. out. println ("finalMethod: I =" + I);} private final void priFinalMethod () {System. out. println ("Person: priFinalMethod");} public static void main (String [] args) {Person per = new Person (); Student stu = new Student (); person per1 = stu; per. priFinalMethod (); stu. priFinalMethod (); per1.priFinalMethod ();}}

 

Student class:

Package human; public class Student extends Person {String stuNumber; int score; public Student () {}// note 18: the subclass cannot override the final-modified method of the parent class. // final void finalMethod () {// int I = 2; // System. out. println ("finalMethod: I =" + I); //} final void priFinalMethod () {System. out. println ("Student: priFinalMethod ");}}

EduBackground class:
package human;//public class EduBackground extends FinalClass {public class EduBackground {    String primarySchool;    String secondarySchool;    String juniorHSchool;    String seniorHSchool;    String university;        public EduBackground() {            }}

 

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.