有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一个用户定义的类分数,它包含几个构造函数和成员方法。我想创建一个单独的“独立函数”类,它使用两个分数实例作为参数,要么创建第三个分数,要么修改并返回它传递的其中一个实例

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

效用类需要与分数体分开定义。我需要几个不同的分数实例,但永远不需要实例化FractionUtility。这使它看起来像是一个静态类,但当我这样做时,它会抛出错误——通常非静态分数变量不能从静态上下文访问

我知道在main()之外定义这两个类,然后导入它们是有意义的,但我不知道该怎么做,也不知道如果这样做,会应用什么规则


共 (1) 个答案

  1. # 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();
    }
    }