I have a user-defined class Fraction which contains several constructors and member methods. I want to create a class of separate "standalone functions" which use two instances of Fraction as arguments to either create a third Fraction or modify and return one of the instances it is passed.
class MyFractionProject{
public static void main(String[] args){
class Fraction{
private int numerator;
private int denominator;
public Fraction(){
numerator = 0;
denominator = 1;
}//default constructor
public Fraction (int num, int denom){
numerator = num;
denominator = denom;
}//sample constructor
//other constructors
//accessors and mutators (setters and getters) are here
public Fraction multiply(Fraction otherFraction){
Fraction result = new Fraction(//multiply the Fractions);
return result;
}//sample member method, calls a constructor and accessor
//a bunch of other member methods are here
}//end Fraction
//New standalone utility class goes here:
class FractionUtility{
//suite of ~5 functions which take two Fraction objects as arguments
//and return a Fraction object, either one of the arguments or a new
//instance
public static FractionUtility UtilityMultiply(Fraction fr1, Fraction fr2){
//lots of stuff
}//Does this HAVE to return a FractionUtility, or can it return a Fraction?
//Can I declare variables outside the static FractionUtility methods if they
//will be needed every time the method is called? Will they be accessible
//inside the static methods? Do I need to instead declare them inside every
//static method so that they're visible each time I call the method?
}//end FractionUtility
//bunch of other stuff in main(), successfully uses Fraction but not
//FractionUtility
}//end main()
}
The Utility class is required to be defined separate from the body of Fraction. I need to have several different instances of Fractions, but never need to instantiate FractionUtility. This makes is seem like making it a static class would work, but when I do it throws errors--generally that nonstatic Fraction variables can't be accessed from a static context.
I could see how it would make sense to define both classes outside of main() and then import them, but I have no idea how to do that or what rules apply if I do.