logo

Метод Getter і Setter у прикладі Java

Методи getter і setter часто використовуються в програмуванні на Java. Методи отримання та встановлення в Java широко використовуються для доступу та керування значеннями полів класу. Зазвичай поля класу прикрашені специфікатором приватного доступу. Таким чином, щоб отримати доступ до них, специфікатори публічного доступу використовуються з методами getter і setter.

Необхідність методу отримання та встановлення

Хтось може заперечити, що оголосити поля класу як публічні та видалити методи getter і setter. Однак такий стиль кодування є поганим, і можна додати якісь абсурдні значення полям класу. Розберемося в цьому на прикладі.

 public class GetterSetterExample { public salary; public storeSalaryDB(int salary) { // code for storing the salary in the database } // main method public static void main(String argvs[]) { GetterSetterExample obj = new GetterSetterExample(); obj.salary = -50000; // storing salary in database obj.storeSalaryDB(salary); } } 

Зверніть увагу, що код зберігає негативну зарплату в базі даних, що є неправильним. Організація ніколи не зараховує негативну зарплату на рахунок працівника. Присвоєння абсурдної суми змінній salary сталося через те, що вона оголошена зі специфікатором публічного доступу. Правильний спосіб написання наведеного вище коду:

 public class GetterSetterExample { private salary; // a setter method that assign a // value to the salary variable void setSalary(int s) { if(s <0 ) { s="-s;" } this.salary="s;" a getter mehtod to retrieve the salary int getsalary() return this.salary; public storesalarydb(int salary) code for storing in database system.out.println('the ') main method static void main(string argvs[]) creating an object of class gettersetterexample obj="new" gettersetterexample(); obj.setsalary(-50000); obj.storesalarydb(salary); < pre> <p>Now, we can see better control over what we send to the database to store. Whenever the salary is negative, we are converting the salary into a positive value, and then we are sending it to the database to store. Thus, no matter what value we send to the setter method, the if-block of the setter method takes care of the absurd value and thus gives better control on the salary value.</p> <h2>Getter Setter Java Program</h2> <p> <strong>FileName:</strong> GetterSetterExample1.java</p> <pre> class Employee { // class member variable private int eId; private String eName; private String eDesignation; private String eCompany; public int getEmpId() { return eId; } public void setEmpId(final int eId) { this.eId = eId; } public String getEmpName() { return eName; } public void setEmpName(final String eName) { // Validating the employee&apos;s name and // throwing an exception if the name is null or its length is less than or equal to 0. if(eName == null || eName.length() <= 0) { throw new illegalargumentexception(); } this.ename="eName;" public string getempdesignation() return edesignation; void setempdesignation(final edesignation) this.edesignation="eDesignation;" getempcompany() ecompany; setempcompany(final ecompany) this.ecompany="eCompany;" for printing the values @override tostring() str="Employee: [id = " + getempid() ', name=" + getEmpName() + " , designation=" + getEmpDesignation() + " company=" + getEmpCompany() + " ]'; str; main class. class gettersetterexample1 method static main(string argvs[]) creating an object of employee final emp="new" employee(); details are getting set using setter methods. emp.setempid(107); emp.setempname('kathy'); emp.setempdesignation('software tester'); emp.setempcompany('xyz corporation'); displaying 'tostring()' method, which uses getter methods system.out.println(emp.tostring()); < pre> <p> <strong>Output:</strong> </p> <pre> Employee: [id = 107, name = Kathy, designation = Software Tester, company = XYZ Corporation] </pre> <h2>Bad Practices in Getter and Setter Methods</h2> <p>There are some common bad practices that people usually do when they deal with the getter and setter methods.</p> <h3>Bad Practice 1:</h3> <p>Using getter and setter for the variable that is declared with low restricted scope.</p> <pre> public salary; void setSalary(int s) { salary = s; } int getSalary() { return salary; } </pre> <p>It is evident that from the main method, one can directly access the variable salary, which is not only bad but also makes the presence of the getter and setter methods irrelevant.</p> <h3>Bad Practice 2:</h3> <p>Using an object reference in the setter method. Consider the following program.</p> <p> <strong>FileName:</strong> GetterSetterExample2.java</p> <pre> class ABC { private int[] val; void setVal(int[] arr) { this.val = arr; // line 7 } // for displaying the value // present in the val array void display() { int size = (this.val).length; for(int i = 0; i <size; i++) { system.out.print(this.val[i] + ' '); } main class public gettersetterexample2 method static void main(string argvs[]) instantiating the abc obj="new" abc(); int mainarr[]="{3," 4, 6, 8, 78, 9}; invoking setter obj.setval(mainarr); display obj.display(); updating value at 0th index mainarr[0]="-1;" system.out.println(); < pre> <p> <strong>Output:</strong> </p> <pre> 3 4 6 8 78 9 -1 4 6 8 78 9 </pre> <p> <strong>Explanation:</strong> </p> <p>References are a bit tricky to deal with! In the above code, at line 43, the value got updated at the 0th index for array mainArr[]. However, it also got reflected in the array val[]. It should not happen as val[] array is declared private; hence, it is expected that any code outside of the class ABC should not modify it. However, because of the references, everything is messed up. The setter method setVal() expecting a reference of an int array, and at line 7, the reference of the int arr[] is getting copied to val[]. Note that the reference variable arr[] is storing the reference of the array mainArr[]. Thus, we can say val[] is storing the reference of the mainArr[].</p> <p>Therefore, whatever we change in the mainArr[] also gets reflected in the val[] array, which violates the purpose of the setter method. Also, there is no meaning in adding the private access specifier to the val[] array; because one can change the value of the val[] array in the main method, which is evident by looking at the output.</p> <p>A better way of writing the above code is:</p> <p> <strong>FileName:</strong> GetterSetterExample3.java</p> <pre> class ABC { private int[] val; void setVal(int[] arr) { int size = arr.length; // allocating the memory as // per the array arr size val = new int[size]; // line 11 for(int i = 0; i <size; 17 53 i++) { copying the value one by into val array this.val[i]="arr[i];" line } for displaying present in void display() int size="(this.val).length;" for(int i="0;" < size; system.out.print(this.val[i] + ' '); main class. public class gettersetterexample3 method static main(string argvs[]) instantiating abc obj="new" abc(); mainarr[]="{3," 4, 6, 8, 78, 9}; invoking setter obj.setval(mainarr); display obj.display(); updating at 0th index mainarr[0]="-1;" system.out.println(); again pre> <p> <strong>Output:</strong> </p> <pre> 3 4 6 8 78 9 3 4 6 8 78 9 </pre> <p> <strong>Explanation:</strong> </p> <p>In the above code, we are doing the deep copy of elements of the array arr[]. In line 11, we are creating an entirely new array. Thus, the val[] is not referring to the arr[]. Also, in line 17, only values of the element are getting copied. Therefore, when we change the value of the 0th element at line 53, the change is not reflected in the val[]. Thus, the above code respects the encapsulation of the private member variable val[].</p> <h3>Bad Practice 3:</h3> <p>Returning an object reference in the getter method. Observe the following program.</p> <p> <strong>FileName:</strong> GetterSetterExample4.java</p> <pre> class ABC { private int[] val = {67, 43, 68, 112, 70, 12}; // the getter method public int[] getVal() { // returning the reference return val; // line 9 } // for displaying the value // present in the val array void display() { int size = (this.val).length; for(int i = 0; i <size; 42 i++) { system.out.print(this.val[i] + ' '); } main class. public class gettersetterexample4 method static void main(string argvs[]) instantiating the abc obj="new" abc(); invoking getter and storing result int arr[]="obj.getVal();" display obj.display(); updating value at 0th index arr[0]="-1;" line system.out.println(); again < pre> <p> <strong>Output:</strong> </p> <pre> 67 43 68 112 70 12 -1 43 68 112 70 12 </pre> <p> <strong>Explanation:</strong> </p> <p>The above code is not handling the references properly. The getter method is returning the reference of the array. The arr[] is storing the reference of the array val[], which is declared private in the class ABC. Because of exposing the reference to the outer world, arr[] can manipulate the val[], and thus, the encapsulation of the class ABC is breached. The proper way to handle the above is:</p> <p> <strong>FileName:</strong> GetterSetterExample5.java</p> <pre> class ABC { private int[] val = {67, 43, 68, 112, 70, 12}; // the getter method public int[] getVal() { int size = val.length; // creating a new array int temp[] = new int[size]; // copying the content of the array to temp array for(int i = 0; i <size; 54 i++) { temp[i]="val[i];" } return temp; for displaying the value present in val array void display() int size="(this.val).length;" for(int i="0;" < size; system.out.print(this.val[i] + ' '); main class. public class gettersetterexample5 method static main(string argvs[]) instantiating abc obj="new" abc(); invoking getter and storing result arr[]="obj.getVal();" display obj.display(); updating at 0th index arr[0]="-1;" line system.out.println(); pre> <p> <strong>Output:</strong> </p> <pre> 67 43 68 112 70 12 67 43 68 112 70 12 </pre> <p> <strong>Explanation:</strong> In the above code, the reference of the private array is not sent to the outside world. In the getter method, a new array is created whose reference is sent to the main method. Therefore, when the value at the 0th index gets changed at line 54, that change impacts the temp[] array, not the private array val[]. Thus, the encapsulation of the class ABC is maintained, as the reference of the array val[] is not exposed to the outside world.</p> <h4>Note 1: For primitive data types (int, char, etc.), one does not need to create a copy in the getter and setter methods, as the concept of references is absent for the primitive data types.</h4> <h4>Note 2: Strings object types also work on the references. However, unlike the above examples, one does not need to take care of the String references exposed to the outside world. It is because Strings are immutable. Thus, when one manipulates the string in the main method (or anywhere else), a new String object is created, and the previous one remains untouched.</h4> <p> <strong>FileName:</strong> GetterSetterExample6.java</p> <pre> class ABC { private String str = null; // a setter method void setVal(String s) { // reference is getting copied this.str = s; } // for displaying the string void display() { System.out.println( &apos;The String is: &apos; + this.str); } } // Main class. public class GetterSetterExample6 { // main method public static void main(String argvs[]) { // creating an object of the class ABC ABC obj = new ABC(); // input string String inputStr = &apos;Hello India!&apos;; // invoking the setter method obj.setVal(inputStr); obj.display(); // manipulation is not allowed! // it leads to the creation of the new string inputStr = &apos;Hello World!&apos;; obj.display(); } } </pre> <p> <strong>Output:</strong> </p> <pre> The String is: Hello India! The String is: Hello India! </pre> <hr></size;></pre></size;></pre></size;></pre></size;></pre></=></pre></0>

Погана практика в методах Getter і Setter

Є деякі поширені погані практики, які люди зазвичай роблять, коли мають справу з методами отримання та встановлення.

Погана практика 1:

Використання getter і setter для змінної, яка оголошена з низькою обмеженою областю.

 public salary; void setSalary(int s) { salary = s; } int getSalary() { return salary; } 

Очевидно, що з основного методу можна отримати прямий доступ до змінної зарплати, що не тільки погано, але й робить наявність методів getter і setter нерелевантною.

Погана практика 2:

Використання посилання на об’єкт у методі налаштування. Розглянемо наступну програму.

1 мільйон номер

Ім'я файлу: GetterSetterExample2.java

 class ABC { private int[] val; void setVal(int[] arr) { this.val = arr; // line 7 } // for displaying the value // present in the val array void display() { int size = (this.val).length; for(int i = 0; i <size; i++) { system.out.print(this.val[i] + \' \'); } main class public gettersetterexample2 method static void main(string argvs[]) instantiating the abc obj="new" abc(); int mainarr[]="{3," 4, 6, 8, 78, 9}; invoking setter obj.setval(mainarr); display obj.display(); updating value at 0th index mainarr[0]="-1;" system.out.println(); < pre> <p> <strong>Output:</strong> </p> <pre> 3 4 6 8 78 9 -1 4 6 8 78 9 </pre> <p> <strong>Explanation:</strong> </p> <p>References are a bit tricky to deal with! In the above code, at line 43, the value got updated at the 0th index for array mainArr[]. However, it also got reflected in the array val[]. It should not happen as val[] array is declared private; hence, it is expected that any code outside of the class ABC should not modify it. However, because of the references, everything is messed up. The setter method setVal() expecting a reference of an int array, and at line 7, the reference of the int arr[] is getting copied to val[]. Note that the reference variable arr[] is storing the reference of the array mainArr[]. Thus, we can say val[] is storing the reference of the mainArr[].</p> <p>Therefore, whatever we change in the mainArr[] also gets reflected in the val[] array, which violates the purpose of the setter method. Also, there is no meaning in adding the private access specifier to the val[] array; because one can change the value of the val[] array in the main method, which is evident by looking at the output.</p> <p>A better way of writing the above code is:</p> <p> <strong>FileName:</strong> GetterSetterExample3.java</p> <pre> class ABC { private int[] val; void setVal(int[] arr) { int size = arr.length; // allocating the memory as // per the array arr size val = new int[size]; // line 11 for(int i = 0; i <size; 17 53 i++) { copying the value one by into val array this.val[i]="arr[i];" line } for displaying present in void display() int size="(this.val).length;" for(int i="0;" < size; system.out.print(this.val[i] + \' \'); main class. public class gettersetterexample3 method static main(string argvs[]) instantiating abc obj="new" abc(); mainarr[]="{3," 4, 6, 8, 78, 9}; invoking setter obj.setval(mainarr); display obj.display(); updating at 0th index mainarr[0]="-1;" system.out.println(); again pre> <p> <strong>Output:</strong> </p> <pre> 3 4 6 8 78 9 3 4 6 8 78 9 </pre> <p> <strong>Explanation:</strong> </p> <p>In the above code, we are doing the deep copy of elements of the array arr[]. In line 11, we are creating an entirely new array. Thus, the val[] is not referring to the arr[]. Also, in line 17, only values of the element are getting copied. Therefore, when we change the value of the 0th element at line 53, the change is not reflected in the val[]. Thus, the above code respects the encapsulation of the private member variable val[].</p> <h3>Bad Practice 3:</h3> <p>Returning an object reference in the getter method. Observe the following program.</p> <p> <strong>FileName:</strong> GetterSetterExample4.java</p> <pre> class ABC { private int[] val = {67, 43, 68, 112, 70, 12}; // the getter method public int[] getVal() { // returning the reference return val; // line 9 } // for displaying the value // present in the val array void display() { int size = (this.val).length; for(int i = 0; i <size; 42 i++) { system.out.print(this.val[i] + \' \'); } main class. public class gettersetterexample4 method static void main(string argvs[]) instantiating the abc obj="new" abc(); invoking getter and storing result int arr[]="obj.getVal();" display obj.display(); updating value at 0th index arr[0]="-1;" line system.out.println(); again < pre> <p> <strong>Output:</strong> </p> <pre> 67 43 68 112 70 12 -1 43 68 112 70 12 </pre> <p> <strong>Explanation:</strong> </p> <p>The above code is not handling the references properly. The getter method is returning the reference of the array. The arr[] is storing the reference of the array val[], which is declared private in the class ABC. Because of exposing the reference to the outer world, arr[] can manipulate the val[], and thus, the encapsulation of the class ABC is breached. The proper way to handle the above is:</p> <p> <strong>FileName:</strong> GetterSetterExample5.java</p> <pre> class ABC { private int[] val = {67, 43, 68, 112, 70, 12}; // the getter method public int[] getVal() { int size = val.length; // creating a new array int temp[] = new int[size]; // copying the content of the array to temp array for(int i = 0; i <size; 54 i++) { temp[i]="val[i];" } return temp; for displaying the value present in val array void display() int size="(this.val).length;" for(int i="0;" < size; system.out.print(this.val[i] + \' \'); main class. public class gettersetterexample5 method static main(string argvs[]) instantiating abc obj="new" abc(); invoking getter and storing result arr[]="obj.getVal();" display obj.display(); updating at 0th index arr[0]="-1;" line system.out.println(); pre> <p> <strong>Output:</strong> </p> <pre> 67 43 68 112 70 12 67 43 68 112 70 12 </pre> <p> <strong>Explanation:</strong> In the above code, the reference of the private array is not sent to the outside world. In the getter method, a new array is created whose reference is sent to the main method. Therefore, when the value at the 0th index gets changed at line 54, that change impacts the temp[] array, not the private array val[]. Thus, the encapsulation of the class ABC is maintained, as the reference of the array val[] is not exposed to the outside world.</p> <h4>Note 1: For primitive data types (int, char, etc.), one does not need to create a copy in the getter and setter methods, as the concept of references is absent for the primitive data types.</h4> <h4>Note 2: Strings object types also work on the references. However, unlike the above examples, one does not need to take care of the String references exposed to the outside world. It is because Strings are immutable. Thus, when one manipulates the string in the main method (or anywhere else), a new String object is created, and the previous one remains untouched.</h4> <p> <strong>FileName:</strong> GetterSetterExample6.java</p> <pre> class ABC { private String str = null; // a setter method void setVal(String s) { // reference is getting copied this.str = s; } // for displaying the string void display() { System.out.println( &apos;The String is: &apos; + this.str); } } // Main class. public class GetterSetterExample6 { // main method public static void main(String argvs[]) { // creating an object of the class ABC ABC obj = new ABC(); // input string String inputStr = &apos;Hello India!&apos;; // invoking the setter method obj.setVal(inputStr); obj.display(); // manipulation is not allowed! // it leads to the creation of the new string inputStr = &apos;Hello World!&apos;; obj.display(); } } </pre> <p> <strong>Output:</strong> </p> <pre> The String is: Hello India! The String is: Hello India! </pre> <hr></size;></pre></size;></pre></size;></pre></size;>

Пояснення:

Справа з посиланнями трохи складна! У наведеному вище коді в рядку 43 значення було оновлено за 0-м індексом для масиву mainArr[]. Однак це також відобразилося в масиві val[]. Цього не повинно статися, оскільки масив val[] оголошено приватним; отже, очікується, що будь-який код поза класом ABC не повинен його змінювати. Однак через довідки все переплутано. Метод установки setVal() очікує посилання на масив int, а в рядку 7 посилання на int arr[] копіюється в val[]. Зауважте, що посилання на змінну arr[] зберігає посилання на масив mainArr[]. Таким чином, ми можемо сказати, що val[] зберігає посилання на mainArr[].

Тому все, що ми змінюємо в mainArr[], також відображається в масиві val[], що порушує призначення методу setter. Крім того, немає сенсу додавати специфікатор приватного доступу до масиву val[]; тому що можна змінити значення масиву val[] у основному методі, що видно, дивлячись на вихід.

Кращий спосіб написання наведеного вище коду:

Ім'я файлу: GetterSetterExample3.java

 class ABC { private int[] val; void setVal(int[] arr) { int size = arr.length; // allocating the memory as // per the array arr size val = new int[size]; // line 11 for(int i = 0; i <size; 17 53 i++) { copying the value one by into val array this.val[i]="arr[i];" line } for displaying present in void display() int size="(this.val).length;" for(int i="0;" < size; system.out.print(this.val[i] + \' \'); main class. public class gettersetterexample3 method static main(string argvs[]) instantiating abc obj="new" abc(); mainarr[]="{3," 4, 6, 8, 78, 9}; invoking setter obj.setval(mainarr); display obj.display(); updating at 0th index mainarr[0]="-1;" system.out.println(); again pre> <p> <strong>Output:</strong> </p> <pre> 3 4 6 8 78 9 3 4 6 8 78 9 </pre> <p> <strong>Explanation:</strong> </p> <p>In the above code, we are doing the deep copy of elements of the array arr[]. In line 11, we are creating an entirely new array. Thus, the val[] is not referring to the arr[]. Also, in line 17, only values of the element are getting copied. Therefore, when we change the value of the 0th element at line 53, the change is not reflected in the val[]. Thus, the above code respects the encapsulation of the private member variable val[].</p> <h3>Bad Practice 3:</h3> <p>Returning an object reference in the getter method. Observe the following program.</p> <p> <strong>FileName:</strong> GetterSetterExample4.java</p> <pre> class ABC { private int[] val = {67, 43, 68, 112, 70, 12}; // the getter method public int[] getVal() { // returning the reference return val; // line 9 } // for displaying the value // present in the val array void display() { int size = (this.val).length; for(int i = 0; i <size; 42 i++) { system.out.print(this.val[i] + \' \'); } main class. public class gettersetterexample4 method static void main(string argvs[]) instantiating the abc obj="new" abc(); invoking getter and storing result int arr[]="obj.getVal();" display obj.display(); updating value at 0th index arr[0]="-1;" line system.out.println(); again < pre> <p> <strong>Output:</strong> </p> <pre> 67 43 68 112 70 12 -1 43 68 112 70 12 </pre> <p> <strong>Explanation:</strong> </p> <p>The above code is not handling the references properly. The getter method is returning the reference of the array. The arr[] is storing the reference of the array val[], which is declared private in the class ABC. Because of exposing the reference to the outer world, arr[] can manipulate the val[], and thus, the encapsulation of the class ABC is breached. The proper way to handle the above is:</p> <p> <strong>FileName:</strong> GetterSetterExample5.java</p> <pre> class ABC { private int[] val = {67, 43, 68, 112, 70, 12}; // the getter method public int[] getVal() { int size = val.length; // creating a new array int temp[] = new int[size]; // copying the content of the array to temp array for(int i = 0; i <size; 54 i++) { temp[i]="val[i];" } return temp; for displaying the value present in val array void display() int size="(this.val).length;" for(int i="0;" < size; system.out.print(this.val[i] + \' \'); main class. public class gettersetterexample5 method static main(string argvs[]) instantiating abc obj="new" abc(); invoking getter and storing result arr[]="obj.getVal();" display obj.display(); updating at 0th index arr[0]="-1;" line system.out.println(); pre> <p> <strong>Output:</strong> </p> <pre> 67 43 68 112 70 12 67 43 68 112 70 12 </pre> <p> <strong>Explanation:</strong> In the above code, the reference of the private array is not sent to the outside world. In the getter method, a new array is created whose reference is sent to the main method. Therefore, when the value at the 0th index gets changed at line 54, that change impacts the temp[] array, not the private array val[]. Thus, the encapsulation of the class ABC is maintained, as the reference of the array val[] is not exposed to the outside world.</p> <h4>Note 1: For primitive data types (int, char, etc.), one does not need to create a copy in the getter and setter methods, as the concept of references is absent for the primitive data types.</h4> <h4>Note 2: Strings object types also work on the references. However, unlike the above examples, one does not need to take care of the String references exposed to the outside world. It is because Strings are immutable. Thus, when one manipulates the string in the main method (or anywhere else), a new String object is created, and the previous one remains untouched.</h4> <p> <strong>FileName:</strong> GetterSetterExample6.java</p> <pre> class ABC { private String str = null; // a setter method void setVal(String s) { // reference is getting copied this.str = s; } // for displaying the string void display() { System.out.println( &apos;The String is: &apos; + this.str); } } // Main class. public class GetterSetterExample6 { // main method public static void main(String argvs[]) { // creating an object of the class ABC ABC obj = new ABC(); // input string String inputStr = &apos;Hello India!&apos;; // invoking the setter method obj.setVal(inputStr); obj.display(); // manipulation is not allowed! // it leads to the creation of the new string inputStr = &apos;Hello World!&apos;; obj.display(); } } </pre> <p> <strong>Output:</strong> </p> <pre> The String is: Hello India! The String is: Hello India! </pre> <hr></size;></pre></size;></pre></size;>

Пояснення:

У наведеному вище коді ми робимо глибоке копіювання елементів масиву arr[]. У рядку 11 ми створюємо абсолютно новий масив. Таким чином, val[] не посилається на arr[]. Крім того, у рядку 17 копіюються лише значення елемента. Таким чином, коли ми змінюємо значення 0-го елемента в рядку 53, зміна не відображається у val[]. Таким чином, наведений вище код поважає інкапсуляцію приватної змінної-члена val[].

Погана практика 3:

Повернення посилання на об’єкт у методі getter. Дотримуйтеся наступної програми.

Ім'я файлу: GetterSetterExample4.java

 class ABC { private int[] val = {67, 43, 68, 112, 70, 12}; // the getter method public int[] getVal() { // returning the reference return val; // line 9 } // for displaying the value // present in the val array void display() { int size = (this.val).length; for(int i = 0; i <size; 42 i++) { system.out.print(this.val[i] + \' \'); } main class. public class gettersetterexample4 method static void main(string argvs[]) instantiating the abc obj="new" abc(); invoking getter and storing result int arr[]="obj.getVal();" display obj.display(); updating value at 0th index arr[0]="-1;" line system.out.println(); again < pre> <p> <strong>Output:</strong> </p> <pre> 67 43 68 112 70 12 -1 43 68 112 70 12 </pre> <p> <strong>Explanation:</strong> </p> <p>The above code is not handling the references properly. The getter method is returning the reference of the array. The arr[] is storing the reference of the array val[], which is declared private in the class ABC. Because of exposing the reference to the outer world, arr[] can manipulate the val[], and thus, the encapsulation of the class ABC is breached. The proper way to handle the above is:</p> <p> <strong>FileName:</strong> GetterSetterExample5.java</p> <pre> class ABC { private int[] val = {67, 43, 68, 112, 70, 12}; // the getter method public int[] getVal() { int size = val.length; // creating a new array int temp[] = new int[size]; // copying the content of the array to temp array for(int i = 0; i <size; 54 i++) { temp[i]="val[i];" } return temp; for displaying the value present in val array void display() int size="(this.val).length;" for(int i="0;" < size; system.out.print(this.val[i] + \' \'); main class. public class gettersetterexample5 method static main(string argvs[]) instantiating abc obj="new" abc(); invoking getter and storing result arr[]="obj.getVal();" display obj.display(); updating at 0th index arr[0]="-1;" line system.out.println(); pre> <p> <strong>Output:</strong> </p> <pre> 67 43 68 112 70 12 67 43 68 112 70 12 </pre> <p> <strong>Explanation:</strong> In the above code, the reference of the private array is not sent to the outside world. In the getter method, a new array is created whose reference is sent to the main method. Therefore, when the value at the 0th index gets changed at line 54, that change impacts the temp[] array, not the private array val[]. Thus, the encapsulation of the class ABC is maintained, as the reference of the array val[] is not exposed to the outside world.</p> <h4>Note 1: For primitive data types (int, char, etc.), one does not need to create a copy in the getter and setter methods, as the concept of references is absent for the primitive data types.</h4> <h4>Note 2: Strings object types also work on the references. However, unlike the above examples, one does not need to take care of the String references exposed to the outside world. It is because Strings are immutable. Thus, when one manipulates the string in the main method (or anywhere else), a new String object is created, and the previous one remains untouched.</h4> <p> <strong>FileName:</strong> GetterSetterExample6.java</p> <pre> class ABC { private String str = null; // a setter method void setVal(String s) { // reference is getting copied this.str = s; } // for displaying the string void display() { System.out.println( &apos;The String is: &apos; + this.str); } } // Main class. public class GetterSetterExample6 { // main method public static void main(String argvs[]) { // creating an object of the class ABC ABC obj = new ABC(); // input string String inputStr = &apos;Hello India!&apos;; // invoking the setter method obj.setVal(inputStr); obj.display(); // manipulation is not allowed! // it leads to the creation of the new string inputStr = &apos;Hello World!&apos;; obj.display(); } } </pre> <p> <strong>Output:</strong> </p> <pre> The String is: Hello India! The String is: Hello India! </pre> <hr></size;></pre></size;>

Пояснення:

Наведений вище код неправильно обробляє посилання. Метод getter повертає посилання на масив. Arr[] зберігає посилання на масив val[], який оголошено приватним у класі ABC. Через відкриття посилання на зовнішній світ arr[] може маніпулювати val[], і таким чином порушується інкапсуляція класу ABC. Правильний спосіб вирішення вищевказаного:

Ім'я файлу: GetterSetterExample5.java

 class ABC { private int[] val = {67, 43, 68, 112, 70, 12}; // the getter method public int[] getVal() { int size = val.length; // creating a new array int temp[] = new int[size]; // copying the content of the array to temp array for(int i = 0; i <size; 54 i++) { temp[i]="val[i];" } return temp; for displaying the value present in val array void display() int size="(this.val).length;" for(int i="0;" < size; system.out.print(this.val[i] + \\' \\'); main class. public class gettersetterexample5 method static main(string argvs[]) instantiating abc obj="new" abc(); invoking getter and storing result arr[]="obj.getVal();" display obj.display(); updating at 0th index arr[0]="-1;" line system.out.println(); pre> <p> <strong>Output:</strong> </p> <pre> 67 43 68 112 70 12 67 43 68 112 70 12 </pre> <p> <strong>Explanation:</strong> In the above code, the reference of the private array is not sent to the outside world. In the getter method, a new array is created whose reference is sent to the main method. Therefore, when the value at the 0th index gets changed at line 54, that change impacts the temp[] array, not the private array val[]. Thus, the encapsulation of the class ABC is maintained, as the reference of the array val[] is not exposed to the outside world.</p> <h4>Note 1: For primitive data types (int, char, etc.), one does not need to create a copy in the getter and setter methods, as the concept of references is absent for the primitive data types.</h4> <h4>Note 2: Strings object types also work on the references. However, unlike the above examples, one does not need to take care of the String references exposed to the outside world. It is because Strings are immutable. Thus, when one manipulates the string in the main method (or anywhere else), a new String object is created, and the previous one remains untouched.</h4> <p> <strong>FileName:</strong> GetterSetterExample6.java</p> <pre> class ABC { private String str = null; // a setter method void setVal(String s) { // reference is getting copied this.str = s; } // for displaying the string void display() { System.out.println( &apos;The String is: &apos; + this.str); } } // Main class. public class GetterSetterExample6 { // main method public static void main(String argvs[]) { // creating an object of the class ABC ABC obj = new ABC(); // input string String inputStr = &apos;Hello India!&apos;; // invoking the setter method obj.setVal(inputStr); obj.display(); // manipulation is not allowed! // it leads to the creation of the new string inputStr = &apos;Hello World!&apos;; obj.display(); } } </pre> <p> <strong>Output:</strong> </p> <pre> The String is: Hello India! The String is: Hello India! </pre> <hr></size;>

Пояснення: У наведеному вище коді посилання на приватний масив не надсилається в зовнішній світ. У методі getter створюється новий масив, посилання на який надсилається в основний метод. Таким чином, коли значення 0-го індексу змінюється в рядку 54, ця зміна впливає на масив temp[], а не на приватний масив val[]. Таким чином, зберігається інкапсуляція класу ABC, оскільки посилання на масив val[] не розкривається зовнішньому світу.

Примітка 1. Для примітивних типів даних (int, char тощо) не потрібно створювати копію в методах getter і setter, оскільки концепція посилань відсутня для примітивних типів даних.

Примітка 2. Типи об’єктів String також працюють із посиланнями. Однак, на відміну від наведених вище прикладів, не потрібно піклуватися про посилання на String, відкритий зовнішньому світу. Це тому, що рядки незмінні. Таким чином, коли хтось маніпулює рядком у основному методі (або де-небудь ще), створюється новий об’єкт String, а попередній залишається недоторканим.

Ім'я файлу: GetterSetterExample6.java

 class ABC { private String str = null; // a setter method void setVal(String s) { // reference is getting copied this.str = s; } // for displaying the string void display() { System.out.println( &apos;The String is: &apos; + this.str); } } // Main class. public class GetterSetterExample6 { // main method public static void main(String argvs[]) { // creating an object of the class ABC ABC obj = new ABC(); // input string String inputStr = &apos;Hello India!&apos;; // invoking the setter method obj.setVal(inputStr); obj.display(); // manipulation is not allowed! // it leads to the creation of the new string inputStr = &apos;Hello World!&apos;; obj.display(); } } 

Вихід:

 The String is: Hello India! The String is: Hello India!