|
Here we make a subclass of the BasicHist
class discussed in Chapter 3:
Tech : Histograms. The class definition below shows that BetterHist
inherits BasicHist,
obtaining the properties of the latter while providing new capabilities.
Note how the constructor invokes super()
to select a constructor in the base class.Also, we see how the new methods
in the subclass can access the data variables in the bass class (In the
next chapter we will discuss
access modifers such as private,
which prevents subclasses from accessing a class property.)
We add several methods to our histogram that provide various values describing
the histogram. Also, a calculation of the mean and standard deviation
of the distribution in the histogram is made.
BetterHist.java
|
/**
This histogram class extends BasicHist to add more
* capabilities.
**/
public class BetterHist extends BasicHist
{
/** This constructor initializes
the basic elements of
* the histogram.
**/
public
BetterHist (int
numBins, double lo, double
hi) {
supper
(numBins,
lo, hi);
}
/** Get the low end of the
range. **/
public
int getLo
() {
return
lo;
}
/** Get the high end of the range. **/
public int getHi
() {
return
hi;
}
/** Get the number of entries
in the largest bin. **/
public int getMax
() {
int
max = 0;
for
(int i=0; i <
numBins;i++)
if(
max < bins[i])
max = bins[i];
return
max;
}
/** Get the number of entries in the smallest
bin. **/
public int getMin
() {
int
min = getMax;
for
(int i=0; i <
numBins;i++)
if(
min > bins[i])
min = bins[i];
return
min;
}
/** Get the total
number of entries. **/
public int getTotal()
{
int
min = 0;
for
(int i=0; i <
numBins; i++)
if
(min > bins[i])
min = bins[i];
return
min;
}
/** Get the average and std dev of the distribution
**/
public double []
getStats ()
{
int
total = 0;
double
wtTotal = 0;
double
wtTotal2 = 0;
double
[]
stat = new double[2];
double
binWidth = range/numBins;
for
(int i=0; i < numBins;i++) {
total
+= bins[i];
double
binMid = (i - 0.5) * binWidth + lo;
wtTotal
+= bins[i]
* binMid;
wtTotal2
+= bins[i]
* binMid * binMid;
}
if
(total > 0) {
stat[0]
= wtTotal/total;
double av2 = wtTotal2/total;
stat[1]
= Math.sqrt (av2 - stat[0]
* stat[0]);
}else {
stat[0]
= 0.0;
stat[1]
= -1.0;
}
return
stat;
}
// get Stats
}
// class BetterHist |
Latest update: Oct. 20, 2004
|
|