我有一個用戶定義的類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正文分開定義。我需要有幾個不同的分數實例,但從不需要實例化FractionUtility。這使得它看起來像是一個靜態類會起作用,但是當我這樣做時會拋出錯誤 - 通常不能從靜態上下文訪問非靜態分數變量。
我可以看到在main()之外定義兩個類然後導入它們是有意義的,但我不知道如何去做,或者如果我這樣做了什麼規則。
在'MyUtilityClass' *的方法應該*是靜態的。這隻意味着你不能在沒有實例的情況下訪問'MyUtilityClass'的實例成員。這並不意味着你不能訪問其他類中的實例成員,只要你有一個實例可以訪問它們。請提供一個你需要做的事情的具體例子*和* MyClass'的所有成員來完成這個任務。正如所寫的,你並不真正問一個可回答的問題。 – cdhowie 2014-11-03 20:51:22
爲什麼選擇C++標籤? – 2014-11-03 20:52:47
這個'main()'方法應該屬於'MyClass'類嗎?它必須屬於* some *類。如果您嘗試編譯僅包含您所呈現內容的Java源文件,那麼編譯器肯定會發出錯誤。 – 2014-11-03 20:57:27