Lesson 6 | Adding behavior with methods |
Objective | Give objects behavior using methods. |
Adding Behavior with Methods
As you now know, objects possess two fundamental characteristics:
- state and
- behavior.
The state of an object is dictated by its member variables, while the behavior of the object is determined by its
methods.
returnType methodName(parameter1) {
// Code goes here MethodBody
}
int square(int n){
return n*n;
}
boolean isHungry() {
return hungry;
}
This method makes a good addition to the Lion
class.
The name of the method is isHungry()
, and it returns data of type boolean
. The isHungry()
method accepts no parameters, as evident by the empty parentheses following the method name.
The code in the isHungry()
method simply returns the value of the hungry
member variable.
Simple Class - Exercise
A method is a discrete section of code that can be called to perform a specific task. Following is the syntax used to define methods in Java: