logo

Getter és Setter módszer Java példában

A Getter és Setter metódusokat gyakran használják a Java programozásban. Getter és setter metódusok Java-ban széles körben használják az osztálymezők értékeinek eléréséhez és kezeléséhez. Általában az osztálymezőket privát hozzáférés-specifikátor díszíti. Így ezek eléréséhez nyilvános hozzáférési specifikátorokat használnak a getter és setter metódusokkal.

A Getter és Setter módszer igénye

Vitatkozhatunk amellett, hogy az osztálymezőket nyilvánossá nyilvánítsuk, és távolítsuk el a getter és setter metódusokat. Azonban egy ilyen kódolási stílus rossz, és az osztálymezőket abszurd értékkel ruházhatjuk fel. Értsük meg egy példa segítségével.

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

Figyelje meg, hogy a kód rossz fizetést tárol az adatbázisban. Egy szervezet soha nem ír jóvá negatív fizetést egy alkalmazott számláján. Abszurd összeg hozzárendelése a fizetési változóhoz azért történt, mert nyilvános hozzáférési specifikátorral van deklarálva. A fenti kód helyes írási módja:

 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>

Rossz gyakorlatok a getter és szetter módszerekben

Vannak általánosan elterjedt rossz gyakorlatok, amelyeket az emberek általában követnek, amikor a getter és setter módszerekkel foglalkoznak.

1. rossz gyakorlat:

Getter és setter használata az alacsony korlátozott hatókörrel deklarált változóhoz.

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

Nyilvánvaló, hogy a fő módszerből közvetlenül hozzá lehet férni a változó fizetéshez, ami nem csak rossz, de irrelevánssá teszi a getter és setter módszerek jelenlétét.

2. rossz gyakorlat:

Objektumhivatkozás használata a setter metódusban. Fontolja meg a következő programot.

markdown aláhúzás

Fájl név: 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;>

Magyarázat:

A referenciákkal kicsit nehézkes foglalkozni! A fenti kód 43. sorában a mainArr[] tömb 0. indexénél frissült az érték. Ez azonban a val[] tömbben is tükröződött. Ennek nem szabad megtörténnie, mivel a val[] tömb privátnak van nyilvánítva; ezért elvárható, hogy az ABC osztályon kívüli kódok ne módosítsák azt. Viszont a referenciák miatt minden össze van borulva. A setVal() setter metódus egy int tömb hivatkozását várja, és a 7. sorban az int arr[] hivatkozása a val[]-ba másolódik. Vegye figyelembe, hogy az arr[] referenciaváltozó a mainArr[] tömb hivatkozását tárolja. Így azt mondhatjuk, hogy a val[] a mainArr[] hivatkozását tárolja.

Ezért bármit is változtatunk a mainArr[]-ban, az a val[] tömbben is tükröződik, ami sérti a setter metódus célját. Ezenkívül nincs értelme a privát hozzáférés-specifikátor hozzáadásának a val[] tömbhöz; mert a fő metódusban megváltoztathatjuk a val[] tömb értékét, ami a kimenetre nézve nyilvánvaló.

A fenti kód jobb írási módja a következő:

Fájl név: 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;>

Magyarázat:

A fenti kódban az arr[] tömb elemeinek mélymásolatát végezzük. A 11. sorban egy teljesen új tömböt hozunk létre. Így a val[] nem az arr[]-ra utal. Ezenkívül a 17. sorban csak az elem értékei kerülnek másolásra. Ezért amikor az 53. sorban megváltoztatjuk a 0. elem értékét, a változás nem tükröződik a val[]-ban. Így a fenti kód tiszteletben tartja a val[] privát tag változó beágyazását.

3. rossz gyakorlat:

Objektumhivatkozás visszaadása a getter metódusban. Vegye figyelembe a következő programot.

Fájl név: 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;>

Magyarázat:

A fenti kód nem megfelelően kezeli a hivatkozásokat. A getter metódus a tömb hivatkozását adja vissza. Az arr[] a val[] tömb hivatkozását tárolja, amely az ABC osztályban privátként van deklarálva. A külső világra való hivatkozás feltárása miatt az arr[] manipulálhatja a val[]-t, és így az ABC osztály beágyazása megsérül. A fentiek kezelésének megfelelő módja:

Fájl név: 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;>

Magyarázat: A fenti kódban a privát tömb hivatkozása nem kerül kiküldésre a külvilág felé. A getter metódusban egy új tömb jön létre, amelynek hivatkozása a fő metódusra kerül. Ezért, amikor a 0. index értéke megváltozik az 54. sorban, ez a változás a temp[] tömböt érinti, nem a val[] privát tömböt. Így az ABC osztály beágyazása megmarad, mivel a val[] tömb referenciája nincs kitéve a külvilágnak.

tavaszi csizma építészet

1. megjegyzés: Primitív adattípusoknál (int, char stb.) nem kell másolatot készíteni a getter és setter metódusokban, mivel a hivatkozás fogalma hiányzik a primitív adattípusoknál.

2. megjegyzés: A karakterláncok objektumtípusai a hivatkozásokon is működnek. A fenti példákkal ellentétben azonban nem kell gondoskodni a külvilágnak kitett String hivatkozásokról. Ez azért van, mert a húrok megváltoztathatatlanok. Így amikor a fő metódusban (vagy bárhol máshol) manipuláljuk a karakterláncot, akkor egy új String objektum jön létre, és az előző érintetlen marad.

Fájl név: 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(); } } 

Kimenet:

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