next up previous contents index
Next: Index Up: Java Previous: Constructors   Contents   Index


Inheritance

Inheritance in Java is straightforward - in the definition of the class, one specified the parent by use of extends. As an example, let us introduce a stats_ext class as a child of the stats class by adding an attribute standard_dev, representing the standard deviation of the data points, and a method std_dev to calculate it. Such a class is
// file stats_ext.java
public class stats_ext extends stats {
    public double standard_dev;

    public void stdev() {
        int j;
        double sum=0.0;
        for(j=0; j<N; j++) {
            sum += (values[j] - average)*(values[j] - average);
        }
        standard_dev = Math.sqrt(sum / (double) (N-1));
    }
}
with an example of it's use being
// file data.java
public class data {
    public static void main(String[] args) {
        stats_ext my_data = new stats_ext();
        my_data.avg();
        my_data.stdev();
        System.out.println("The average is " + my_data.average);
        System.out.println("The standard deviation is " + my_data.standard_dev);
    }
}
This program can be compiled and run as
  javac stats.java
  javac stats_ext.java
  javac data.java
  java data