7. Accessing Method
Until now, we have covered the topic of constructors. In this section, we will shift our focus to accessing methods.
Let us take the same example that we did previously, which is about Employee
, in this section, we will add a new method to display the name
and the ID_number
of the Employee
. Note that there will be no argument, as well as no return value for our method. Since no return value is set for our method, the method will be void.
Let us write our method, called displayNameAndID_number
. Inside this method, we will be using System.out.println
syntax to display the name and ID number:
public class Employee{
String name;
int ID_number;
Employee (String name, int ID_number){
this.name = name;
this.ID_number = ID_number;
}
void displayNameAndID_Number(){
System.out.println("Employee name: " +name);
System.out.println("Employee ID number: " +ID_number);
}
public static void main (String[] args) {
Employee E1 = new Employee("Tony", 220101);
Employee E2 = new Employee("Tina", 220302);
}
}
To access this method, once we had created the object, as per example here, we had created object E1
, and E2
. The format to call the method is ‘object name
’.’method name
’. For this example, the object name is E1
, and the method name is displayNameAndID_number
. Therefore, the code can be written as follows:
E1.displayNameAndID_Number();
//ObjectName.MethodName
And for this example, it will be written in public static void, after we created the Employee object:
public class Employee{
String name;
int ID_number;
Employee (String name, int ID_number){
this.name = name;
this.ID_number = ID_number;
}
void displayNameAndID_Number(){
System.out.println("Employee name: " +name);
System.out.println("Employee ID number: " +ID_number);
}
public static void main (String[] args) {
Employee E1 = new Employee("Tony", 220101);
Employee E2 = new Employee("Tina", 220302);
E1.displayNameAndID_Number();
E2.displayNameAndID_Number();
}
}
Recall what happen previously when object E1
is created, when we first declared the variable and instantiate the object, the default name for E1
will be null
, and the ID_number
will be 0
. Then, we perform initialization by assigning the name to be Tony
, and ID_number
is 220101
.
So, at this stage, for object E1
, it’s information for name
and ID_number
has been updated as per instructed. It will no longer be null
and 0
, but now, it will be Tony
and 220101
.
Every time we call for our method here (displayNameAndID_number
), which is a method to display the name
and ID number
, specifically for object E1
, the name will always be Tony
, and the ID_number
will be 220101
.
Notice that from the output, for Employee name: Tony, and Employee ID number: 220101
, is the result of code
E1.displayNameAndID_Number();
which is taken from the method displayNameAndID_number
. Even without passing argument to the method, since we had initialized the object, the value of name
and ID_number
will stay in the memory of object E1
.