我正在寻找什么样的构造函数和访问修饰符组合?

时间:2014-11-03 20:49:19

标签: java class constructor utility

我有一个用户定义的类Fraction,它包含几个构造函数和成员方法。我想创建一类独立的独立功能"它使用两个Fraction实例作为参数来创建第三个Fraction或修改并返回它传递的实例之一。

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()
}

Utility类需要与Fraction主体分开定义。我需要有几个不同的Fractions实例,但从不需要实例化FractionUtility。这使得它看起来像是静态类可以工作,但是当我这样做时会抛出错误 - 通常不能从静态上下文访问非静态分数变量。

我可以看到在main()之外定义两个类然后导入它们是有意义的,但我不知道如何做到这一点或者如果我这样做适用什么规则。

1 个答案:

答案 0 :(得分:1)

好吧,您似乎只想在同一个文件中声明几个不相关的类。

那是什么静态内部类。

例如,你可以这样做:

public class Something {

static class MyClass {
    private int data = 0;

    public MyClass() {
    }
    public MyClass(int data) {
        this.data = data;
    }

    public MyClass makeNew( MyClass otherinstance ) {
        MyClass result = new MyClass( this.data + otherinstance.data );
        return result;
    }
}


static class MyUtilityClass {
}

public static void main( String[] args ) {
    MyClass myClass = new MyClass();
    MyClass copy = myClass.makeNew( new MyClass() );
    MyUtilityClass utilityClass = new MyUtilityClass();
}
}