19-02-2013, 04:06 PM
How to Write and Use a Java Method
How to Write.pdf (Size: 51.87 KB / Downloads: 24)
Simple Java Method
Sometimes the terms function and method are used interchangeably. They are virtually the
same. The correct terminology for Java is method. It is a set of commands that can be used
over again. In this, they share similarities with sub routines in the early days of
programming.
Visibility means who can access it. If it is public, anyone who has access to your class file
can access the method. In some circumstances, this is perfectly fine. If the method is
private, only the functions inside of that class can call the method. This is used as utility
methods to do something you do not want just anyone who uses the class to do. Protected
gives public function to all child classes.
How to Write and Use a Java Method
Return type is void if you do not want the method to give you any data back. It would be
used for such things as a method that prints out something. Any other return requires a
return statement with the type of data it returns. For example, if you add two integers and
want the results of that integer, your return type would be int.
Name of the method is anything you choose that is not already used in the class (unless you
are overloading the method which is beyond the scope of this article)
If you want the method to do something with the data you supply it, you also need to
include parameters within the ( ) You include what data type it is and give that parameter a
name (ie: you are declaring a local variable for that method only)