Java Methods
In this chapter you will learn:
Description
Classes usually consist of two things: instance variables and methods. Instance variables are the data part of a class, while the methods defines the behaviours of a class.
Syntax
This is the general form of a method:
type name(parameter-list) {
// body of method
}
type specifies the type of data returned by the method. If the method does not return a value, its return type must be void. The name of the method is specified by name.
The parameter-list is a sequence of type and identifier pairs separated by commas.
Parameters receives the value of the arguments passed to the method.
If the method has no parameters, then the parameter list will be empty.
Example
Add a method to Box,as shown here:
class Box {/*from w w w. ja v a2s .c o m*/
int width;
int height;
int depth;
void calculateVolume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
public class Main {
public static void main(String args[]) {
Box mybox1 = new Box();
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox1.calculateVolume();
}
}
This program generates the following output:
Next chapter...
What you will learn in the next chapter:
- How to return from a method
- Syntax for return value from a method
- Example - How to return a value from a method
- Example - How to return an object from a method
Java Object
Java Object Reference Variable
Java Methods
Java Method ReturnJava Method Parameters
Java Class Constructors
Java Default Constructor
Java Constructor Parameters
Java this Keyword
Java static keyword
Java Method Overload
Java Constructors Overload
Java Method Argument Passing
Java Method Recursion
Java Nested Class
Java Anonymous Classes
Java Local Classes
Java Member Classes
Java Static Member Classes
Java Class Variables
Java main() Method
Java Class Inheritance
Java super keyword
Java Method Overriding
Java Constructor in hierarchy
Polymorphism
Java final keyword
Java Abstract class
Java Class Access Control
Java Package
Java Packages Import
Java Interface
Java Interface as data type
Java interface as build block
Java instanceof operator
Java Source Files