Section 6.1 Defining Classes in Java
You have already seen how to define classes in Java. Itβs unavoidable for even the simplest of programs. In this section we will look at how we define classes to create our own data types. Lets start by creating a fraction class to extend the set of numeric data types provided by our language. The requirements for this new data type are as follows:
-
Given a numerator and a denominator create a new Fraction.
-
When a fraction is printed it should be simplified.
-
Two fractions can be added or subtracted
-
Two fractions can be multiplied or divided
-
Two fractions can be compared
-
A fraction and an integer can be added together.
-
Given a list of Fractions that list should be sortable by the default sorting function.
Here is a mostly complete implementation of a Fraction class in Python that we will refer to throughout this section:
The instance variables (data members) we will need for our fraction class are the numerator and denominator. Of course in Python we can add instance variables to a class at any time by simply assigning a value to
objectReference.variableName, whereas in Java all data members must be declared up front.
The declarations of instance variables can come at the beginning of the class definition or the end. Cay Horstman, author of the βCore Javaβ books puts the declarations at the end of the class. I like them at the very beginning so you see the variables that are declared before you begin looking at the code that uses them. With that in mind the first part of the Fraction class definition is as follows:
public class Fraction {
private Integer numerator;
private Integer denominator;
}
Notice that we have declared the numerator and denominator to be private. This means that the compiler will generate an error if another method tries to write code like the following:
Fraction f = new Fraction(1,2);
Integer y = f.numerator * 10;
Direct access to instance variables is not allowed in Java. Therefore if we legitimately want to be able to access information such as the numerator or the denominator for a particular fraction we must have a getter method that returns the needed value. Hence, it is a very common programming practice to both provide getter methods and setter methods when needed for instance variables in Java.
public Integer getNumerator() {
return numerator;
}
public void setNumerator(Integer numerator) {
this.numerator = numerator;
}
public Integer getDenominator() {
return denominator;
}
public void setDenominator(Integer denominator) {
this.denominator = denominator;
}
You have attempted of activities on this page.
