C SC 160 Chapter 7: Defining Your Own Classes (advanced)
major resource: An Introduction to Object-Oriented Programming with Java, fourth
edition,
Wu, McGraw Hill, 2006
[ previous | schedule | next ]
/**
* Converts a given amount in dollars into
* an equivalent amount in a foreign currency.
*
* @param dollar the amount in dollars to be converted
*
* @return amount in foreign currency
*/
public double fromDollar(double dollar) {
return (dollar * exchangeRate) ;
}
The above comments, when processed by javadoc in the context of a fully-commented CurrencyConverter
class, will produce two portions of the documentation.
![]() |
![]() |
Study closely the correspondence between the code and the resulting documentation. Nice!
Here is example constructor from a CurrencyConverter class that has one instance variable, double exchangeRate;
public CurrencyConverter( double rate ) {
exchangeRate = rate;
}
Programmers often provide multiple constructors having default values for different
combinations of instance variables. CurrencyConverter has only one instance
variable, so consider one additional constructor that gives it a default value
of 1.0.
public CurrencyConverter( ) {
this(1.0);
}
This constructor has no parameters, and works by invoking the other constructor with an argument
value of 1.0. It is not unusual to define one constructor to do all the work and define the others to
call it with the desired configuration of supplied and default values.
Here's another example of the technique, which shows 4 constructors
import java.awt.Color;
public class Square {
private double height;
private Color color;
public final double DEFAULT_HEIGHT = 1.0;
public final Color DEFAULT_COLOR = Color.BLACK;
public Square(double ht, Color col) {
height = ht;
color = col;
}
public Square(double ht) {
this(ht, DEFAULT_COLOR);
}
public Square(Color col) {
this(DEFAULT_HEIGHT, col);
}
public Square( ) {
this(DEFAULT_HEIGHT, DEFAULT_COLOR);
}
/********* remainder of class omitted *********/
}
This is called overloading. The compiler can distinguish between different versions of the constructor based on the different
parameter types and counts (int versus String parameter, 1 versus 2 parameters, etc)
The examples above show a new use for the reserved word this. It is used to explicitly invoke one constructor from inside another constructor in the same class. Using this technique, one can define a multiple-parameter constructor to do the construction work then invoke it from lesser-or-no parameter constructors that pass on default initial values.
There is a related concept called overriding, that we have not considered. Overriding occurs when you write a method that has the same name and parameters as one of your inherited methods. The new version overrides the inherited one.
public String sumString(int a, int b) {
String result = new Integer(a+b).toString();
return result;
}
Call it in a statement like System.out.println(sumString(39290,9923));