2013-12-19 5 views
-1

참고 : 다른 게시물을 살펴 보았지만 여전히 매우 분실했습니다.다른 클래스의 개인 변수에 액세스

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

어떻게 : 나는 다른 클래스에있는 코드의이 작품에 접근 할 필요가

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; 
    } 

:

내가 하나 개의 클래스에있는 개인 변수에 대한 코드입니다 나는 이것을한다? 나는 일종의 수식어를 사용해야한다고 생각하지만, 어떻게 그것을 구현해야하는지 모르겠습니다.

+0

당신은 당신의 방법 이외의 변수를 선언하고 그 변수에 대한 게터/setter 메소드를 만들 수로 그것을 호출하는 processTransaction 방법

public static int readFile(String fileName) { } 

로 변경? – Dan

+0

질문을받지 못했습니다. 나는 당신이'private int readFile (String fileName)'메소드에 접근하기를 원합니까? 필드가 맞지 않아? – 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

다른 클래스의 개인 변수에 직접 액세스 할 수 없습니다. 그것이 사적이라고 선언하는 전체 시점입니다. 당신이해야 할 일은 A 클래스에 settergetter 메서드를 사용하고 B 클래스에서 get 메서드를 호출하는 것입니다.

0

your comment에 따라 private int readFile(String fileName) 메서드에 액세스 할 수 있습니다. 메소드의 수정자를 public 또는 protected으로 변경하십시오. 또한 액세스 방법이 static이므로 static으로 변경해야합니다.

그래서

ClassName.readFile("file_name.extn"); 
관련 문제