2013-12-19 90 views
-1

注意:在訪問私有變量:我已經看過其他職位,但我仍然完全迷失了方向。從另一個類

這是我在一個類中的私有變量的代碼:

private int readFile(String fileName) 
{ 
try 
{ 
      File f = new File(fileName); 
      Scanner input = new Scanner(f); 
      while(input.hasNextLine()) 
      { 
        String s = input.nextLine(); 
        String[ ] sArr = s.split(" "); 
        String animal = sArr[ 0 ]; 
        double cost = Double.parseDouble(sArr [ 1 ]); 
        boolean penNeeded = Boolean.parseBoolean(sArr[ 2 ]); 
        boolean available = Boolean.parseBoolean(sArr[ 3 ]); 
        Pet p = new Pet(animal, cost, penNeeded, available); 
        if (count < animalList.length) 
        { 
         animalList[count] = p; 
         count++; 
        } 
      } 
      input.close(); 
     } 
     catch(Exception e) 
     { 
      System.out.println("Error reading the file:"); 
      System.out.println(e); 
      e.printStackTrace(); 
     } 

     return count; 
    } 

我需要訪問它在這片位於另一個類代碼:

static public void processTransaction(String fileName, PettingZoo pz) 
{ 
    try 
    { 
     // variable should be accessed here     
    } 
    catch(Exception e) 
    { 
     System.out.println("Error reading the file:"); 
     System.out.println(e); 
     e.printStackTrace(); 
    } 
} 

哪有我這樣做?我認爲我需要使用某種修飾符,但我不知道如何實現它。

+0

你可以聲明變量的方法之外,然後創建該變量的getter/setter方法? – Dan

+0

我沒有得到你的問題。我想你想訪問'私人int readFile(字符串文件名)'方法?不是正確的? – Jayamohan

+0

*什麼*「私人變量」?你顯示一個聲明爲「private」的方法......這意味着你不能從另一個類訪問它。 –

回答

2

如果你想訪問一個私有變量,你可以使用getter和setter方法。

實施例:

private int variable = 5; //<--- your private variable of class A 

// a public method (into the same class A) 
// that allows the sharing of your private variable 
public int getVariable() { 
    return variable; 
} 

現在,可以調用從其它類(B)的方法getVariable()並採取(A類)的專用變量的值。

2

你不能直接從另一個類訪問私有變量。這就是宣稱它是私密的。你需要做的是使用settergetter方法A類,然後調用從Bget方法。

0

作爲每your comment你可以通過改變改性的方法的訪問的方法private int readFile(String fileName)。該法的修改改爲publicprotected。另外由於訪問方法是static,您需要將方法更改爲static

因此改變它作爲

public static int readFile(String fileName) 
{ 

} 

processTransaction方法來調用它,

ClassName.readFile("file_name.extn");