J2EEOnline J2EE 






Java TM Fundamentals I  «Prev  Next»
Lesson 6Adding behavior with methods
ObjectiveGive objects behavior using 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.
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:
returnType methodName(parameter1) {
  // Code goes here MethodBody
}
int square(int n){
  return n*n;
}
It is often necessary for methods to return information regarding the task they have performed. The ReturnType specifies the type of data that a method returns. The MethodName is the name of the method.
A method is also capable of receiving parameters that somehow determine how it functions. Method parameters are identified in the Parameters of the method definition. The actual code for the method is located in the MethodBody. Following is an example of a method:
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

Click the Exercise link below to define a simple class.
Simple Class - Exercise