Tags: Java foundation


Why is the Date object set to obsolete?

In the early days of Java learning, we will use such an object as Date, but we all know that this object is not recommended in the book. Why??

Since Java is an object-oriented language, using an object class like Date to describe time is perfectly correct: it satisfies most people’s needs, and it can be extended!

So why don’t we use Date objects to manipulate time? Because it’s not well designed!

Java objects are designed to encapsulate, and the Date class is only used to represent points in time. The operation time should be taken care of by another class! Date objects, however, have methods for manipulating time. This is unreasonable.

  • Therefore, if we want to manipulate time, we tend to use the Calendar or LocalDate classes

Date objects are designed to break encapsulation!

When we define a class with a private property of type Date, for example:


public class A{


	private Date hiredate ;

	setHiredate(){}
	getHiredate(){
		returnhiredate; }}Copy the code

When someone needs the class’s time, we use the get method to return the member variable. It’s a given. It’s our norm.

However, when the outside world gets our Date member variable, we can use date.settime () to change the time. Since our private member variables depend on Date, modifying Date’s data is equivalent to modifying our private member variables!

In other words, the outside world can take the Date object and change the value of our private member variable. It’s not through the interface that we’ve given. This seriously breaks encapsulation!

Of course, there are other ways to remedy it:

  • When we return the Date object, we return a copy, rather than returning the original object
  • This way, we don’t have to worry about outsiders manipulating our private variables through Date objects.

getHiredate(){

	return (Date)hiredate.clone();
}

Copy the code

If you find this article helpful, give the author a little encouragement