A Java class can have a method. This is a piece of code which can be used on members of the class. In the example below, a class called Square is created. The Square class has a method called display_area, which calculates and displays the area of the square:
andrew@UBUNTU:~/Java$ cat Square.java
public class Square
{
double width;
double area;
public void display_area()
{
area = width * width;
System.out.println("Area = " + area);
}
}
class SquareExample
{
public static void main(String args[])
{
Square my_square = new Square();
my_square.width = 5;
my_square.display_area();
}
}
andrew@UBUNTU:~/Java$ javac Square.java
andrew@UBUNTU:~/Java$ java SquareExample
Area = 25.0
andrew@UBUNTU:~/Java$