logo

Геттер и Сеттер метод у Јава примеру

Геттер и сеттер методе се често користе у Јава програмирању. Геттер и сеттер методе у Јави се широко користе за приступ и манипулисање вредностима поља класе. Обично су поља класе украшена спецификацијом приватног приступа. Дакле, да би им се приступило, користе се спецификације јавног приступа са методама геттер и сеттер.

Потреба за методом Геттер и Сеттер

Може се рећи да се поља класе декларишу као јавна и да се уклањају методе добијања и постављања. Међутим, такав стил кодирања је лош и може се ставити нека апсурдна вредност у поља класе. Хајде да то разумемо уз помоћ примера.

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

Обратите пажњу на то да код чува негативну плату у бази података која је погрешна. Организација никада не уписује негативну плату на рачун запосленог. Додељивање апсурдног износа варијабли плате догодило се зато што је декларисана са спецификацијом јавног приступа. Исправан начин да се напише горњи код је:

 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>

Лоше праксе у методама Геттер и Сеттер

Постоје неке уобичајене лоше праксе које људи обично раде када се баве методама добијања и постављања.

грешка: не могу пронаћи или учитати главну класу

Лоша пракса 1:

Коришћење геттера и сетера за променљиву која је декларисана са ниским ограниченим опсегом.

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

Евидентно је да се из главног метода може директно приступити варијабилној плати, што је не само лоше, већ чини ирелевантним присуство геттер и сеттер метода.

Лоша пракса 2:

Коришћење референце објекта у методи постављача. Размотрите следећи програм.

Назив документа: ГеттерСеттерЕкампле2.јава

 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. индексу за низ маинАрр[]. Међутим, то се такође одразило у низу вал[]. То не би требало да се деси пошто је низ вал[] проглашен приватним; стога се очекује да било који код изван класе АБЦ не би требало да га мења. Међутим, због референци је све збркано. Метод за постављање сетВал() очекује референцу инт низа, а у реду 7, референца инт арр[] се копира у вал[]. Имајте на уму да референтна променљива арр[] чува референцу низа маинАрр[]. Дакле, можемо рећи да вал[] чува референцу маинАрр[].

јава за типове петљи

Стога, шта год да променимо у маинАрр[] такође се одражава у низу вал[], што нарушава сврху методе постављања. Такође, нема смисла додавати спецификацију приватног приступа низу вал[]; јер се може променити вредност низа вал[] у главном методу, што је евидентно гледањем на излаз.

Бољи начин писања горњег кода је:

Назив документа: ГеттерСеттерЕкампле3.јава

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

Објашњење:

У горњем коду радимо дубоку копију елемената низа арр[]. У реду 11, креирамо потпуно нови низ. Дакле, вал[] се не односи на арр[]. Такође, у реду 17 се копирају само вредности елемента. Стога, када променимо вредност 0. елемента у реду 53, промена се не одражава у вал[]. Дакле, горњи код поштује енкапсулацију променљиве приватног члана вал[].

преименуј линукс фасциклу

Лоша пракса 3:

Враћање референце објекта у методу геттер. Обратите пажњу на следећи програм.

делимични деривати латекса

Назив документа: ГеттерСеттерЕкампле4.јава

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

Објашњење:

Горњи код не рукује референцама исправно. Геттер метода враћа референцу низа. Арр[] чува референцу низа вал[], који је декларисан као приватни у класи АБЦ. Због излагања референце на спољашњи свет, арр[] може да манипулише вал[], и на тај начин је прекршена енкапсулација класе АБЦ. Правилан начин да се поступи са горе наведеним је:

Назив документа: ГеттерСеттерЕкампле5.јава

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

Објашњење: У горњем коду, референца приватног низа се не шаље у спољашњи свет. У геттер методи се креира нови низ чија се референца шаље главном методу. Стога, када се вредност на 0. индексу промени у реду 54, та промена утиче на низ темп[], а не на приватни низ вал[]. Тако се одржава енкапсулација класе АБЦ, пошто референца низа вал[] није изложена спољашњем свету.

Напомена 1: За примитивне типове података (инт, цхар, итд.), није потребно креирати копију у методама геттер и сеттер, пошто концепт референци недостаје за примитивне типове података.

Напомена 2: Типови објеката низова такође раде на референцама. Међутим, за разлику од горњих примера, не треба водити рачуна о стринг референцама изложеним спољашњем свету. То је зато што су стрингови непроменљиви. Дакле, када неко манипулише стрингом у главном методу (или било где другде), ствара се нови Стринг објекат, а претходни остаје нетакнут.

Назив документа: ГеттерСеттерЕкампле6.јава

 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!