Section 6.2 Writing a constructor
Once you have identified the instance variables for your class the next thing to consider is the constructor. In Java, constructors have the same name as the class and are declared public. They are declared without a return type. So any method that is named the same as the class and has no return type is a constructor. Our constructor will take two parameters: the numerator and the denominator.
public Fraction(Integer top, Integer bottom) {
num = top;
den = bottom;
}
There are a couple of important things to notice here. First, you will notice that the constructor does not have a
self parameter. You will also notice that we can simply refer to the instance variables by name without the self prefix, because they have already been declared. This allows the Java compiler to do the work of dereferencing the current Java object. Java does provide a special variable called this that works like the self variable. In Java, this is typically only used when it is needed to differentiate between a parameter or local variable and an instance variable. For example this alternate definition of the the Fraction constructor uses this to differentiate between parameters and instance variables.
public Fraction(Integer num, Integer den) {
this.num = num;
this.den = den;
}
You have attempted of activities on this page.
