[英]Changing the value of a “File” parameter without creating a new instance of a class
我這里有點問題。
我在這些方法中聲明一個新對象“ Fleet”:
public void run() throws FileNotFoundException
{
File file = new File(getFile());
Fleet fleet = new Fleet(file);
buildFleet(file, fleet);
}
private void buildFleet(File file, Fleet fleet) throws FileNotFoundException
{
fleet.addVehicle(Honda);
userMenu(fleet);
}
最后一行調用userMenu()方法。 在這種方法中,我需要能夠在Fleet中更改“ File”的值,而無需創建該類的新實例。
private void userMenu(Fleet fleet) throws FileNotFoundException
{
PrintWriter pw = new PrintWriter("temp.txt");
File file = new File("temp.txt");
fleet = new Fleet(file);
this.createMenu();
choice = this.menu.getChoice();
while(choice != 8)
{
switch(choice)
{
case 1:
//Do stuff
fleet.addVehicle(Honda);
break;
}
}
另外,不允許創建任何新的班級數據。 有什么建議么?
關於Fleet
類中的文件的setter呢?
public class Fleet {
private File file;
...
public void setFile( File file ){
this.file = file;
}
}
然后,您可以通過調用以下方法來調用此方法來更改Fleet對象中的文件:
fleet.setFile( myNewFile );
解決了:
我變了:
private void userMenu() throws FileNotFoundException
{
PrintWriter pw = new PrintWriter("temp.txt");
File file = new File("temp.txt");
至:
private void userMenu(Fleet fleet) throws FileNotFoundException
{
PrintWriter pw = new PrintWriter("temp.txt");
File file = new File("temp.txt");
fleet.file = file;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.