Next: Inheritance
Up: Java
Previous: Classes
Contents
Index
Constructors
As with C++, it is possible within the class definition
to introduce a constructor to be run when defining
an object. To illustrate this, let us consider the
previous example and move the functionality of the
set_values method, used to populate the
array of data points, into a constructor:
// file stats.java
public class stats {
int N = 200;
public int[] values;
public double average;
public stats() {
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;
}
}
As with C++, the constructor in Java is the same name
as the class. An example of the use of this class is
// file data.java
public class data {
public static void main(String[] args) {
stats my_data = new stats();
my_data.avg();
System.out.println("The average is " + my_data.average);
}
}
with the constructor being run when the new stats()
call is made.