To return the reference type object cautiously in the accessor

Source: Internet
Author: User

One of the three characteristics of object-oriented is encapsulation, the domain (variable) in the class, as far as possible using private, if you really want to access, you can provide get and set, to avoid the damage of encapsulation.

However, if a reference type object is returned in a get accessor, it may also be modified by the outside world, thereby damaging the encapsulation. Such as:

public class Employee {
	private Date hireday;
	Public Date Gethireday () {return
		this.hireday;
	}
	
	private String name;
	Public Employee (String name) {
		this.name = name;
	}
	public boolean equals [Employee other] {return
		name.equalsignorecase (other.name);
	}
}

		Employee Zhang3 = new Employee ("Zhang3");
		Date d = zhang3.gethireday ();
		D.settime (D.gettime ()-10000000);

This is something I had never thought of before.

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.