Class methods
Operations on objects in Java are called
methods.
Methods are like math functions: they can take
argumentsand
return a value. On the other hand, methods in Java also
have access to all fields of an object.
To create a method in a class, you must include it in the class. For example, we can define a
print(age)
method that will print information about our book and display a warning if the user is not yet old enough for that book.
class Book
{
String name;
String authorName;
int ageRequirement;
String text;
int pageCount;
// create a print method
void print(int age)
{
System.out.< span style="color:#7d9029">println("Name: " +name);
System.out.< span style="color:#7d9029">println("Author: " +authorName);
System.out.< span style="color:#7d9029">println("Number of pages: "+Integer.toString span>(ageRequirement);
// verification code goes here
}
}
Let's analyze the syntax for creating a method.
1) The first line of a method is its
signature.
2) The return type of the method is written first. Our method does not return any value, so we write
void
.
3) Then in the signature is the name of the method (
print
).
4) In brackets there is a listing of arguments. Arguments are separated by commas. For each argument, its type and name are specified, separated by a space. In our case, there is only one argument, it has the type
int
and the name
age
, so there are no commas.
5) After that comes the method code in curly braces. To return a value from a method, write
return <value>;
. In the example, the method does not return anything, so
return
can be omitted. To prematurely terminate the execution of a method, you can write
return;
.
6) In the class itself, we can refer to the fields of the object of this class by name.