Next: Constructors
Up: Java
Previous: A simple program
Contents
Index
Classes
As a simple illustration of working with classes in
Java, let us construct a class that, for an array
of integers, calculates the average. The basic
class we'll call stats, and will be defined
in a file stats.java:
// file stats.java
public class stats {
int N = 200;
public int[] values;
public double average;
public void set_values() {
int j;
values = new int[N];
for(j=0; j<N; j++) {
values[j] = 1 + (int) (100.0*Math.random());
}
}
public void avg() {
int sum=0, j;
for(j=0; j<N; j++) {
sum += values[j];
}
average = (double) sum / (double) N;
}
}
where, for illustration, we use a random set of 200 integers
between 0 and 100 as a data set, set within the set_values
method. A program illustrating the use of this class is contained in
data.java:
// file data.java
public class data {
public static void main(String[] args) {
stats my_data = new stats();
my_data.set_values();
my_data.avg();
System.out.println("The average is " + my_data.average);
}
}
This can be compiled and run as
javac stats.java
javac data.java
java data
where, on Unix, you may have to set the environment
variable CLASSPATH to the current directory in
order that the stats class file be found.