Page 220 - Cs_withBlue_J_C11_Flipbook
P. 220
9.3.3 Access Specifier
There has to be some restriction on the accessibility of the methods as they can also be accessed by other methods,
same or different class. Hence, access specifiers help a method to be accessed by the objects of the class in different
ways. So, access specifiers are segregated into three different types which are as follows:
• Public: The keyword “Public” is used to give access to the methods to any class.
Example: public int twice (int i)
• Private: The keyword “Private” allows the methods to be accessed only by the same class.
Example: private int twice (int i)
• Protected: The keyword “Protected” allows other methods of the same class and the inherited class to access the
method.
Example: protected int twice (int i)
Note: When no access specifier is used, then by default it is public.
9.3.4 Return Type and Return Statement
A function can be used only when it is called from another function. So, after completing the assigned job, the control
returns back to the part from where it is called. While doing this, it may or may not return a value along with it. Thus,
we may need the return type and return statement.
• Return Statement: This statement is used when the function is returning some value. The returned value may be of
any data type, even non-primitive data types.
• Return Type: If the function is returning a value, then the data type of the value is mentioned here, in this part of
the method definition. The different data types written here are byte, short, int, long, float, double, char or Boolean.
We can also write a string if we want to return a word or a sentence. Other than these, all non-primitive data types
such as array, class, etc. can be used.
In case, the function does not return any value, then the keyword “void” is used in the method definition.
Example:
public int twice (int
i)
{ Return Type
int tw=i*2; Return Statement
return tw;
}
Characteristics of the return Statement
The characteristics of the return statement are as follows:
• It is the last statement in the method, after which the method is terminated.
• Only one value can be returned at a time.
• There might be more than one termination point. But only one return statement will be executed.
For example,
if(a==b)
return true;
else
return false;
• Once a method is terminated using the return statement, there is no other way for it to reappear in the method block.
218218 Touchpad Computer Science-XI

