Preface
Getter method and Setter method:
The Getter method and Setter method are commonly used in object-oriented programming, which are used to access and modify objects' properties (member variables).
What is the getter method?
The Getter method (also known as an accessor) is used to get the property value of an object. It is usually a public non-static method that does not accept any parameters and returns the value of the property. The name of the Getter method often starts with "get" and is followed by the name of the property. For example, if there is an attribute named "age", the corresponding Getter method is named "getAge".
Format: [Access Modifier] Member variable type getXxx(){ return member variable;}
What is the setter method?
The Setter method (also known as a modifier) is used to modify the property value of an object. It is usually a common non-static method that takes a parameter and updates the value of the property with the value of the parameter. The name of the Setter method often starts with "set" and is followed by the name of the attribute. For example, if there is an attribute named "age", the corresponding Setter method is named "setAge".
Format: [Access modifier] void setXxx(Member variable l type parameter) { Member variable = parameter }
The getter method and setter method function:
The use of Getter and Setter methods can effectively control access and modification of object properties, providing encapsulation and security.
1. Through the Getter method, other classes can obtain the value of the attribute without directly accessing the attribute;
2. Through the Setter method, other classes can modify the value of the attribute without directly modifying the attribute.
This allows you to control the access rights of attributes and perform necessary verification and operations.
class Person { private String name;//Set member variable private int age; public String getName(){//Return the value of the member variable of the object return name; } public int getAge() { return age; } //Notice! When the parameter of the method is the same as the member variable name, use this to reference the member variable public void setName(String name) { = name; } public void setAge(int age)throws Exception {//Declare exception if (age >= 0) { = age; } else { throw new Exception("Age cannot be negative!");//throw an exception }
Set up test class:
//Catch exceptiontry{ //Exception code may occurPerson person = new Person(); ("Alice"); (25); ("Name:" + ()); ("age:" + ()); }catch(Exception e){ //Exception code handling (ehetMessage(); } }
In the above example, through the Getter and Setter methods, external classes can access and modify the name and age properties of Person objects, protecting the access and modification of properties.
Benefits of Getter and Setter methods:
- Encapsulation: Through the Getter and Setter methods, you can control the access and modification of attributes.
- Verification and operation: Verification and operation of attributes can be implemented in Getter and Setter methods, such as scope checking, format conversion, etc., to ensure the legitimacy of the data.
- Readability and maintainability: Getter and Setter methods can provide more descriptive and readable code, making the code easier to understand and maintain.
The main differences between Getter method and Setter method:
- Access level: Normally, the properties of a class are declared private to implement the concept of encapsulation, that is, preventing external direct access and modification of properties. To enable external code to safely access and modify the value of a property, getter and setter methods are defined in the class. In this way, external code can get and set the value of the property by calling these methods without directly accessing the property itself.
- Method naming: The getter method usually starts with get, followed by the attribute name, and the first letter of the attribute name is capitalized. The setter method usually starts with set, followed by the attribute name, and the first letter of the attribute name is capitalized.
- Parameter: The setter method requires a parameter to set the value of the property. The getter method does not require parameters.
- Return value: The getter method needs to return the value of the attribute, while the setter method does not need to return
Summarize
Getter and Setter methods are common methods used to access and modify object properties. They provide encapsulation, verification and operation functions. Through standard naming and method signatures, the readability and maintenance of the code can be improved. In object-oriented programming, it is recommended to use Getter and Setter methods to manipulate object properties
Actual list:
1. Create a student class, add getter and setter for each member variable, where the values of the member variable score1 and score2 are between 0 and 100, otherwise an exception will be thrown.
package c7_1student; public class Student {// Define a class private String id;// Set member variables private String name; private String className; private int score1; private int score2; //Writing of getter and setter public String getId() { return id; } public String getName() { return name; } public String getClassName() { return className; } public int getScore1() { return score1; } public int getScore2() { return score2; } public void setId(String id) { = id; } public void setName(String name) { = name; } public void setClassName(String className) { = className; } public void setScore1(int score1) throws Exception { if (score1 < 0 || score1 > 100) { throw new Exception("Not within the score range"); } else { this.score1 = score1; } } public void setScore2(int score2) throws Exception { if (score2 < 0 || score2 > 100) { throw new Exception("Not within the score range"); } else { this.score2 = score2; } } public int sumOfScore() {// Total score return score1 + score2; } public int maxOfScore() {// Calculate the maximum value int max; if (score1 > score2) { max = score1; } else { max = score2; } return max; } }
2. Create a student class object, use a setter to set values for the object, and display relevant information about the object.
package c7_1student; public class TestStudent { public static void main(String[] args) { try { //It is possible to be exception code Student stu1 = new Student();// Create an object ("202322048"); ("Zhang San"); ("First Grade"); stu1.setScore1(100); stu1.setScore2(90); ("Student name is" + ()); ("Name as" + ()); ("Class for" + ()); ("First subject score" + stu1.getScore1()); ("Second Subject Results" + stu1.getScore2()); ("Sum of Results" + ()); ("Maximum" + ()); (); } catch (Exception e) { // If there is an exception, throw an exception (()); }
The above is an example of using getter and setter methods. I hope you don't confuse the usage of these two and their return types.
Summarize
This is the article about the main differences between Getter and Setter methods in Java. For more relevant contents of Getter and Setter methods in Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!