Home > Java > JavaBase > body text

Immutable classes in java and their creation rules

王林
Release: 2019-12-03 16:57:44
Original
3584 people have browsed it

Immutable classes in java and their creation rules

The immutable class, as its name implies, means that this class cannot be reassigned after it is instantiated. The eight packaging classes provided by java and java.lang.String cannot be Change category.

Rules to follow when creating a custom immutable class:

1. Use private and final to modify member variables.

2. Provide a parameterized constructor for initializing member variables.

3. Do not provide setter methods for member variables.

4. If there is a variable class in the member variable, you need to rewrite the hashCode method and equals method in Object.

java video tutorial recommendation: java learning

For example: Create an immutable Person class

public class Person {
    private final String Name;
    private final String gender;
    
    /*
     * 无参构造方法
     */
    public Person(){
        this.Name="";
        this.gender="";
    }
    /*
     * 有参构造方法
     */
    public Person(String Name , String gender){
        this.Name = Name;
        this.gender = gender;
    }
    public String getName() {
        return Name;
    }
    public String getGender() {
        return gender;
    }
    /*
     * 重写hashCode方法
     * (non-Javadoc)
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        return Name.hashCode() + gender.hashCode();
    }
    /*
     * 重写equals方法
     * (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if(this == obj)
            return true;
        if(obj != null && obj.getClass() == this.getClass()){
            Person pe = (Person)obj;
            if(this.getName().equals(pe.getName()) && this.getGender().equals(pe.getGender()))
                return true;
        }
        return false;
    }
Copy after login

The member variables in the above Person class are all Immutable classes, if there are mutable classes in them, then there is a problem with using the above method to create immutable classes. Although the attributes of Person are immutable, the objects referenced by the attributes are mutable,

This will destroy the immutability of Person, such as the following example.

First create a mutable class College

public class College {
    private String collNo;
    private String collName;
    public College(String collNo, String collName) {
        super();
        this.collNo = collNo;
        this.collName = collName;
    }
    public College() {
        super();
    }
    public String getCollNo() {
        return collNo;
    }
    public void setCollNo(String collNo) {
        this.collNo = collNo;
    }
    public String getCollName() {
        return collName;
    }
    public void setCollName(String collName) {
        this.collName = collName;
    }
    @Override
    public String toString() {
        return "College [collNo=" + collNo + ", collName=" + collName + "]";
    }
Copy after login

Reference College

public class Person {
    private final College college;
    public Person() {
        this.college = null;
    }
    public Person(College college) {
        super();
        this.college = college;
    }
    public College getCollege() {
        return college;
    }
    @Override
    public String toString() {
        return "Person [college=" + college + "]";
    }
    public static void main(String[] args){
        College coll = new College("123456","土木工程");
        Person pe = new Person(coll);
        System.out.println("----->" + pe);
        coll.setCollName("信息工程");                      //这样就会改变Person对象
        System.out.println("======>" + pe);
    }
Copy after login

So how can we create an immutable class with mutable attributes? We just need to make the College attribute inaccessible to the program

public class Person {
    private final College college;
    public Person() {
        this.college = null;
    }
    public Person(College college) {
        //创建一个和传入对象有相同属性的College,赋值给成员变量
        this.college = new College(college.getCollNo(),college.getCollName());
    }
    public College getCollege() {
        //创建一个College将属性的值赋值给它并返回
        return new College(this.college.getCollNo(),this.college.getCollNo());
    }
    @Override
    public String toString() {
        return "Person [college=" + college + "]";
    }
Copy after login

The above idea is to separate the connection between the outside world and the variable attributes in the Person class. The program cannot directly act on the attributes, thus creating a variable class attribute. Immutable classes.

Recommended related articles and tutorials: java entry program

The above is the detailed content of Immutable classes in java and their creation rules. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!