Does Making All Fields Lastly Makes The Class Immutable Inward Java?

Does Making All Fields Lastly Makes The Class Immutable Inward Java? - Hallo sahabat BEST LEARNING JAVA, Pada Artikel yang anda baca kali ini dengan judul Does Making All Fields Lastly Makes The Class Immutable Inward Java?, kami telah mempersiapkan artikel ini dengan baik untuk anda baca dan ambil informasi didalamnya. mudah-mudahan isi postingan Artikel core java, Artikel core java interview question, yang kami tulis ini dapat anda pahami. baiklah, selamat membaca.

Judul : Does Making All Fields Lastly Makes The Class Immutable Inward Java?
link : Does Making All Fields Lastly Makes The Class Immutable Inward Java?

Baca juga


Does Making All Fields Lastly Makes The Class Immutable Inward Java?

One of the mutual misconceptions amidst many Java Programmer is that a shape amongst all concluding fields automatically becomes Immutable. This is non correct, you lot tin give the sack easily intermission immutability of for certain shape if the concluding plain it contains is a mutable one, equally we'll run across inwards this article. One of the nearly mutual examples of this is a java.util.Date fields e.g. birthDay, expirtyDate, or joiningDate sort of fields. You stimulate got to live on extra cautious to proceed your class' immutability intact amongst mutable fields. The nearly mutual error inwards this regard happens when Java programmer render reference of the master copy object when a customer enquire e.g. getBirthDay() returns the appointment object pointed past times birthDay field. When you lot render a reference to a mutable object, you lot are sharing ownership of that reference amongst whoever receives it. This tin give the sack intermission invariant, such equally immutability.

Another instance of this sort of designing which tin give the sack intermission immutability is returning collection or array from the getters method e.g. getListOfBooks() returns a listing of books. Once clients acquire that listing it tin give the sack add together novel books, withdraw books too fifty-fifty modify employees without consulting you, thus bypassing whatever rules you lot stimulate got setup to add together or withdraw books from that list.

So, fifty-fifty though, the plain which is pointing to Date or Collection or array object is final, you lot tin give the sack withal intermission the immutability of the shape past times breaking Encapsulation past times returning a reference to the master copy mutable object.



How to save Immutability?

There are 2 ways to avoid this problem, first, don't render getters to mutable objects if you lot tin give the sack avoid it. If you lot must, too so regard returning a re-create or clone of the mutable object. If you lot are returning a collection, you lot could roll it equally an unmodifiable collection. Since nosotros cannot brand an array concluding or unmodifiable inwards Java, I propose avoiding returning an array, instead render an ArrayList past times converting an array to ArrayList equally shown here.

Now, let's run across to a greater extent than or less code to empathize this error inwards trivial fleck to a greater extent than exceptional too and so we'll run across the right code to solve this work past times preserving both Encapsulation too Immutability of class.

I stimulate got a elementary POJO called Person which has three fields, advert which is String, birthday which is Date, too hobbies which are inwards a listing of String. All these fields are final, only I'll present you lot how you lot tin give the sack withal intermission the immutability of Person shape past times returning a reference to the mutable object to the client.

Remember, an Immutable object cannot live on changed ane time created, thus it's value volition ever live on same too whatever modification on an Immutable object should render a novel Immutable object e.g. String is Immutable too when you lot telephone outcry upward toUpperCase() or toLowerCase() or trim() you lot acquire a novel String object.


Here is our Java Program to demonstrate that concluding fields are non plenty to brand a shape Immutable inwards Java:

import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List;  /**  * Java Program to demonstrate that making all  * fields concluding doesn't brand a shape Immutable.  * You tin give the sack withal intermission immutability if you lot render  * reference to mutable objects to client.  *   * @author WINDOWS 8  *  */ public class App {      public static void main(String args[]) {      Calendar cal = Calendar.getInstance();      cal.set(1982, 4, 21);      Date birthDate = cal.getTime();            List hobbies = new ArrayList<>();           hobbies.add("Painting");      hobbies.add("Travelling");      hobbies.add("Fitness");           Person robin = new Person("Robin", birthDate, hobbies);      System.out.println("Before");      System.out.println(robin);            // if it's immutable you lot can't alter the object      Date birthday = robin.getBirthday();      birthday.setTime(System.currentTimeMillis());            List originalHobbies = robin.getHobbies();      originalHobbies.remove(0);      originalHobbies.remove(0);            System.out.println("After");      System.out.println(robin);         }  }  class Person{   private final String name;   private final Date birthday;   private final List hobbies;         public Person(String name, Date birthday, List hobbies){     this.name = name;     this.birthday = birthday;     this.hobbies = hobbies;   }   public String getName() {     return name;   }   public Date getBirthday() {     return birthday;   }   public List getHobbies() {     return hobbies;   }      @Override   public String toString() {     return "Person [name=" + advert + ", birthday=" + birthday + ", hobbies="         + hobbies + "]";   }          }

When you lot run this programme inwards your IDE or from the ascendancy line, you lot volition run across next output:

Before Person [name=Robin, birthday=Fri May 21 10:51:13 GMT+08:00 1982,  hobbies=[Painting, Travelling, Fitness]] Person [name=Robin, birthday=Sun April 09 10:51:13 GMT+08:00 2017,  hobbies=[Fitness]] After

You tin give the sack run across that nosotros stimulate got managed to alter the country of Person object past times changing its birthdate too hobbies. This agency the Person shape is non Immutable fifty-fifty its all fields are final.  Now, let's run across how nosotros tin give the sack solve this problem. If you lot remember, String is Immutable inwards Java too you lot cannot alter its content afterwards creating it.

 One of the mutual misconceptions amidst many Java Programmer is that a shape amongst all fina Does making all fields Final makes the shape Immutable inwards Java?



In gild to save immutability, nosotros demand to render a clone of the mutable Date object too an unmodifiable ArrayList when the customer asks for hobbies.

Here is the modified code:
class Person{   private final String name;   private final Date birthday;   private final List hobbies;         public Person(String name, Date birthday, List hobbies){     this.name = name;     this.birthday = birthday;     this.hobbies = hobbies;   }   public String getName() {     return name;   }   public Date getBirthday() {     return (Date) birthday.clone();   }   public List getHobbies() {     return Collections.unmodifiableList(hobbies);   }      @Override   public String toString() {     return "Person [name=" + advert + ", birthday=" + birthday + ", hobbies="         + hobbies + "]";   }

You tin give the sack run across that inwards the getBirthDay() method, I am returning a clone of Date object too inwards the getHobbies() method, I am returning too unmodifiable collection, which agency if a user tries to add together to a greater extent than or less other hobby it volition fail.

In Java, Strings are immutable only nearly objects are not. Whenever you lot stimulate got a mutator or setter method e.g. setXXX or addXXX that returns void chances are expert that the object is mutable. Some of the mutual examples are ArrayList too LinkedList.

To brand you lot objects immutable brand for certain they solely stimulate got concluding fields that are non arrays (arrays are ever mutable inwards java) too solely render clone or re-create of the mutable object from getter method if you lot stimulate got to, best is to avoid returning references of mutable object altogether.

That's all inwards this article if you lot are interested inwards learning meat Java concepts similar this, I propose you lot read Effective Java, ane of the best mass for every experienced Java programmers.

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!



Demikianlah Artikel Does Making All Fields Lastly Makes The Class Immutable Inward Java?

Sekianlah artikel Does Making All Fields Lastly Makes The Class Immutable Inward Java? kali ini, mudah-mudahan bisa memberi manfaat untuk anda semua. baiklah, sampai jumpa di postingan artikel lainnya.

Anda sekarang membaca artikel Does Making All Fields Lastly Makes The Class Immutable Inward Java? dengan alamat link https://bestlearningjava.blogspot.com/2019/04/does-making-all-fields-lastly-makes.html

Belum ada Komentar untuk "Does Making All Fields Lastly Makes The Class Immutable Inward Java?"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel