search
HomeJavaJavaBaseImmutable classes in java and their creation rules

Immutable classes in java and their creation rules

Dec 03, 2019 pm 04:57 PM
javacreaterule

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;
    }

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 + "]";
    }

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);
    }

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 + "]";
    }

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!

Statement
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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.