Automate getter-setter generator for Java using Python
Last Updated :
02 Nov, 2022
Encapsulation is defined as the wrapping up of data under a single unit. Encapsulation can be achieved by declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables. These public methods are called getters and setters. In practice, it is quite a time consuming and repetitive process to write the getter-setters for all the variables in Java.
Here we are provided with a list of variable names with their data types, we have to print all the getter-setter methods for them while following the basic Java programming conventions.
Algorithm :
- Change the first character of every variable to uppercase.
- Add “get” in the beginning of each changed variable and store them in a list.
- Add “set” in the beginning of each changed variable and store them in a list.
- For every variable and its corresponding datatype, print the getter and setter methods using string concatenations.
Below is the implementation.
Python3
def print_getter_setter(variables, datatypes):
getters = []
setters = []
for var in variables:
getter = "get" + var[ 0 ].capitalize() + var[ 1 :]
getters.append(getter)
setter = "set" + var[ 0 ].capitalize() + var[ 1 :]
setters.append(setter)
for i in range ( len (variables)):
print ( "public " + datatypes[i] + " " + getters[i] +
"() {\n\treturn " + variables[i] + ";\n}\n" )
print ( "public void " + setters[i] + "(" + datatypes[i] +
" " + variables[i] + ") {\n\tthis." + variables[i] +
" = " + variables[i] + ";\n}\n" )
if __name__ = = "__main__" :
variables = [ "abc" , "empId" , "GFG" , "x" ]
datatypes = [ "int" , "float" , "double" , "String" ]
print_getter_setter(variables, datatypes)
|
Output :
public int getAbc() {
return abc;
}
public void setAbc(int abc) {
this.abc = abc;
}
public float getEmpId() {
return empId;
}
public void setEmpId(float empId) {
this.empId = empId;
}
public double getGFG() {
return GFG;
}
public void setGFG(double GFG) {
this.GFG = GFG;
}
public String getX() {
return x;
}
public void setX(String x) {
this.x = x;
}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...