To create a Java read-only class

Source: Internet
Author: User

You can create your own read-only class, and here's a simple example:

: Immutable1.java
//Objects that cannot is modified
//are immune to aliasing.

public class Immutable1 {
  private int data;
  Public Immutable1 (int initval) {
    data = Initval;
  }
  public int Read () {return data;}
  public Boolean nonzero () {return data!= 0;}
  Public Immutable1 quadruple () {return
    new Immutable1 (data * 4);
  }
  static void F (Immutable1 i1) {
    Immutable1 quad = I1.quadruple ();
    System.out.println ("I1 =" + I1.read ());
    System.out.println ("quad =" + Quad.read ());
  }
  public static void Main (string[] args) {
    Immutable1 x = new Immutable1 (a);
    System.out.println ("x =" + X.read ());
    f (x);
    System.out.println ("x =" + X.read ());
  }
} ///:~

All data is private, and you can see that there is no public way to make changes to the data. In fact, the way you really need to modify an object is quadruple (), but it does this by creating a new Immutable1 object with the original object intact.
Method F () takes a Immutable1 object and takes a different action on it, and the output of main () shows no changes to X. Therefore, the X object can be processed many times without causing any harm because it guarantees that the object will not be altered according to the design of the Immutable1 class.

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.