Java keyword---final and transient

Source: Internet
Author: User

first of all, talk about final.

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

Final Variable:        demand:            1 requires a never-changing compilation constant         &NBS P   21 run-time initialized values, do not want to be changed         Benefits:            compile-time calculations to mitigate runtime burdens &nbs P       Extensions:            can decorate basic types and reference objects. When the base type is modified, the value is determined to be constant. When modifying an object reference, once the reference is initialized to an object, it cannot be changed to another object (the object itself can be modified)         blank final        & nbsp Fields that are  final decorated but do not give the initial value             must assign a final assignment in the definition or constructor of the field (must be initialized before final use) in the definitions or constructors of the domain         Note:          If an object is modified at the same time by static and final (compile-time constants), usually in uppercase, underlined link words     & nbsp   Modifier parameters:          If the final decoration parameter indicates that the parameter is readable, but cannot be modified.       Usage examples:     
Private random rand=new random ();p rivate static  random random=new random ();p rivate final int n1=12;private final int n Umber=rand.nextint (+);p rivate  static final int number2=random.nextint (+), @Testpublic void Finaldatatest () { SYSTEM.OUT.PRINTLN (N1); System.out.println ("--------------------"); System.out.println (Rand.nextint (30)); System.out.println ("--------------------"); System.out.println ("After the initial compilation, does not change:" +number); System.out.println ("--------------------"); System.out.println ("After the initial compilation, does not change:" +number2);} /** * Final modifier parameter: This parameter is readable, but cannot be modified. * @param sk * @return */public string finalparam (final String SK) {//sk= "Jeyson"; final parameter cannot be modified return SK;}
Final method:Final can also modify the method to indicate that the method cannot inherit from the quilt class. Benefits of using Final: 1 JDK1.5 Previously, more efficient, JDK1.5 can be ignored after 2 method locking, ensure that the meaning of the method in the subclass is not changed, can not be overridden usage example:
Public final String Finalmethod () {             return ' Hello world ';      }

  

Final class:If you do not want to be inherited by any class, you can use the final decorated class usage example:
  Public final class Finalclasstx {   private int k;     public void Getmyword () {         System. println ("This is a final class, the value of K is" +GETK ());   }  public int getk () {       return k;} public void setk (int k) {this       . k = k;}  }  

Then transient the keyword:

   transient can only modify variables to indicate that the variable cannot be serialized.     Generally we inherit the class of the serializable interface, and the serialization is done automatically, and the variable modified with transient is not serialized to the specified destination when the class is serialized.     So,     1 the variable modified by transient is no longer part of the object persistence, the variable content serialization cannot get access      2 transient can only modify variables , cannot modify methods and classes      3 A static variable can not be serialized, whether or not it is transient modified     Usage Example:  
public class Transientex {public static void main (string[] args) {User user=new User (); User.setusername ("Jeyson"); user . SetPassword ("123456"); System.out.println ("Pre-serialization:"); System.out.println ("Username=" +user.getusername ()); System.out.println ("password=" +user.getpassword ());//serialization of try {ObjectOutputStream os=new objectoutputstream (new FileOutputStream ("C://myresource//test1.txt")); Os.writeobject (user); Os.flush (); Os.close ();} catch (Exception e) {e.printstacktrace ();} Deserialize the try {ObjectInputStream is=new objectinputstream (New FileInputStream ("C://myresource//test1.txt")); user= (user ) Is.readobject (); Is.close (); System.out.println ("After serialization:"); System.out.println ("Username=" +user.getusername ()); System.out.println ("password=" +user.getpassword ());} catch (Exception e) {e.printstacktrace ();} System.out.println ("--------------------------------");}} Class User implements Serializable{private static final long serialversionuid = 1l;private String username;//using transient Private transient String Password;public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;}}

Extension: externalizable

A class that implements the Serializable interface, so serialization is automatically

The class that implements the Externaliazble interface, nothing can be automatically serialized, regardless of whether the use of transient has no effect on the result.     At this point, if serialization is required, you need to manually specify the variable that you want to serialize in the Writeexternal method. Examples of Use:
public class Externalizableex implements externalizable {private transient String name= "ssss"; @Overridepublic void Readexternal (ObjectInput in) throws IOException, ClassNotFoundException {name= (String) In.readobject ();}   @Overridepublic void Writeexternal (ObjectOutput out) throws IOException {out.writeobject (name);} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public static void Main (string[] args) {Externalizableex ex=new Externalizableex (); Ex.setname ("Jeyson"); System.out.println ("Externalizable before Serialization:"); System.out.println (Ex.getname ()); Serialize try {ObjectOutputStream os=new objectoutputstream (New FileOutputStream ("C://myresource//test2.txt")) ; Os.writeobject (ex); Os.flush (); Os.close ();} catch (Exception e) {e.printstacktrace ();}//Deserialize the try {ObjectInputStream is=new objectinputstream (New FileInputStream ( New File ("C://myresource//test2.txt")); ex= (Externalizableex) is.readobject (); Is.close (); System.out.println ("ExterNalizable after serialization: "); System.out.println (Ex.getname ());} catch (Exception e) {e.printstacktrace ();}}}

Statement:

Final mostly from the fourth edition of Java programming ideas

Transient related parts reference from: http://www.cnblogs.com/lanxuezaipiao/p/3369962.html

Java keyword---final and transient

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.