The constructor for the class should call the two methods to
initialize the instance variables jupiter and mars.
The body of the methods will be somewhat difficult to implement. However,
their implementation is irrelevant to the class structure. We can put the
class together without having the implementation. Let us see how we can do
this.
Since the methods are going to return distances we can assume the return
types are ints.
The signature of the one of the methods might be
public int distance_to_mars()
Since the class structure doesn't depend on the implementation of this
method, let's temporarily have it return an arbitray int.
public int distance_to_mars() {
return(0);
}
Likewise we can do something similar for the other instance method. Note
that we will use a different int so that we can make sure the correct
method is being called.
public int distance_to_jupiter() {
return(1);
}
The constructor is going to make a call to these methods to initialize the
instance variables jupiter and mars. So a constructor for this method
would be the following.
public Spaceship() {
jupiter = distance_to_jupiter();
mars = distance_to_mars();
}
The toString method will display the distances found.
public String toString() {
String outputLine = "\n";
outputLine += "Distance to Mars:" + "\t" + mars + "\n";
outputLine += "Distance to Jupiter:" + "\t" + jupiter + "\n";
return(outputLine);
}
In the main method we will create a new instance of the Spaceship class
and send that object to System.out.println.
public static void main(String[] args) {
Spaceship mySpaceship = new Spaceship();
System.out.println(mySpaceship);
}
Now that we have all the peices written let us write our class definition.
public class Spaceship {
int jupiter;
int mars;
public Spaceship() {
jupiter = distance_to_jupiter();
mars = distance_to_mars();
}
public int distance_to_mars() {
return(0);
}
public int distance_to_jupiter() {
return(1);
}
public String toString() {
String outputLine = "\n";
outputLine += "Distance to Mars:" + "\t" + mars + "\n";
outputLine += "Distance to Jupiter:" + "\t" + jupiter + "\n";
return(outputLine);
}
public static void main(String[] args) {
Spaceship mySpaceship = new Spaceship();
System.out.println(mySpaceship);
}
}
When executed the program produces the following output.
Distance to Mars: 0
Distance to Jupiter: 1
Note that in order for the program to execute the implementation of the
methods is irrelevant.
You may take the same approach in your programming assignment.
Let us recall some of the topics we covered yesterday.