Java Reference
In-Depth Information
Tutorial: Breaking the Getter/Setter Code
In Employee:
1.
In the getEmpCity method, comment out the return statement.
The error message will be “This method must return a result of type String.” For methods that return a result, the
type of data returned must be specified in the method header and the return statement must specify the particular
variable to return. In this case, the header specifies that a String variable will be returned and the return statement
identifies empCity. If either of these is missing, the other will be in error.
2.
Uncomment the return statement and delete “String” in the getEmpCity method header.
The error message will be “Return type for the method is missing.” Remember, to return a value, the return
variable type must be specified in the method header and the variable name must be specified in the return
statement.
3. Type the text “String” before the keyword public in the getEmpCity method header.
Notice that the return type is still incorrect and now both the keyword String and the method name are
highlighted as errors. The syntax for specifying the return type requires that it appear after the access modifier and
before the method name. In this case, placing it before the access modifier ( public ) causes an error.
Delete the access modifier public in the getEmpCity method header.
4.
This is a valid method header definition. An access modifier is not required because a default access modifier will
be used.
5.
Type the text “public ” before the text “String” in the getEmpCity method header.
Go to the setEmpCity method and delete the keyword void from the method header.
6.
The error message will say, “Return type for the method is missing.” All methods except constructors must specify
a return type. If a method returns nothing, then the keyword void must be specified as the return type.
Put the void keyword back in the method header.
7.
8.
Change the name of setEmpCity method to p etEmpCity and save the source code.
Because setEmpCity is invoked in the constructor, this causes an error in the Employee class.
9.
Change the name of the method back to s etEmpCity.
10.
Change the getter g etEmpCity name to p etEmpCity and save the source code.
There are no errors flagged in Employee; however, the Navigation tree shows an error in EmpFrame. It's
important to realize that even though RAD says the error is in EmpFrame, in this case the error is in Employee.
RAD is good at identifying errors but not so good at assigning responsibility. Do not follow the error messages and
their suggestions blindly. Many times errors are caused by mismatches between classes, and the programmer will
have to determine which needs to be changed.
11.
Change the getter name back to g etEmpCity and save the source code.
 
Search WWH ::




Custom Search