2014-07-17 2 views
4

나는 자바로 게임을 만들고 있으며, 가장 이상한 버그를 가지고있다. 나는 무기라는 계급을 가지고있다. 그런 다음 primary라는 이름의 인스턴스를 만듭니다. 내가 인스턴스를 생성하고 그것을 보조라고 부른 후에. 어떤 이상한 이유 때문에, 1 차가 2 차 값으로 덮어 쓰게됩니다. 내 강사와 나는 그것을 보았고 그것을 이해할 수 없었다. 여기 코드는 : 당신의 Weapon 클래스의자바 클래스의 인스턴스를 선언하는 이상한 런타임 오류

public class weapon { 
     static String type; 
     static String name; 
     static int weight; 
     static int damage; 
     static int dodge; 
     weapon(String c, String n, int w, int da, int dod) { 

       type = c; 
       name = n; 
       weight = w; 
       damage = da; 
       dodge = dod; 

     } 
     //getters 
     String getType(){ 
       return type; 
     } 
     String getName(){ 
       return name; 
     } 
     Integer getWeight(){ 
       return weight; 
     } 
     Integer getDamage(){ 
       return damage; 
     } 
     Integer getDodge(){ 
       return dodge; 
     } 
     //setters 
     void setType(String c){ 
       c=type; 
     } 
     void setName(String n){ 
       n=name; 
     } 
     void setWeight(Integer w){ 
       w=weight; 
     } 
     void setDamage(Integer da){ 
       damage=da; 
     } 
     void setDodge(Integer dod){ 
       dodge=dod; 
     } 
} 

/*At the top of my main class I create both instances like this because the instances are created in if statements and I need to access them.*/ 
weapon primary; 
weapon secondary; 
//I create primary like this earlier in the code like this 
primary = new weapon("primary","sword", 8, 6, -1); 
//and then when I run this I get the output "sword" "Heavy Sword". 
System.out.println(primary.getName()); 
secondary = new weapon("secondary", "huge sword", 9, 7, -2); 
System.out.println(primary.getName()); 
+2

를 설명 관련 코드는 여기에 있습니다. 덕분에 – Braj

답변

4

귀하의 모든 멤버 변수는 정적으로 정의됩니다

정적 멤버는 클래스 veriables이기 때문에 두 번째 인스턴스의 값이 (첫 번째 우선 이유
static String type; 
    static String name; 
    static int weight; 
    static int damage; 
    static int dodge; 

이 -의 모든 인스턴스에 걸쳐 그 중 하나의 사본이 클래스).

정적 키워드를 제거하면 문제가 해결됩니다.

3

모든 속성은 사용자가 만드는 모든 인스턴스간에 공유하는 의미 정적이다.

인스턴스 변수 대신 static을 제거하면 괜찮을 것입니다.

+0

! 위대한 일을했다. – user2774616

0

모든 멤버 변수는 static으로 선언됩니다. 멤버 변수를 static으로 선언하면 해당 클래스의 모든 객체가 해당 변수의 동일한 복사본을 공유합니다. 하나의 객체가 변수의 값을 변경하면 다른 객체에 대해서도 변경됩니다.

static 키워드 만 제거하면됩니다.

Weapon은 bean 클래스 인 것처럼 보입니다. private 멤버 변수와 public getter/setters를 사용하면 제대로 캡슐화하는 것이 좋습니다.

0

생성 된 각 개체마다 다른 변수가 아닌 클래스 와이드 변수를 사용하여 클래스를 만들었습니다.

대신 사용 : 공유하십시오

public class weapon { 
     private String type; 
     private String name; 
     private int weight; 
     private int damage; 
     private int dodge; 
     weapon(String c, String n, int w, int da, int dod) { 

나는 당신이 당신의 "클래스 필드"와 "객체 필드"를 보장하는 클래스를 정의 할 때 다음과 같은 패턴을 사용하는 것이 좋습니다 것이 아니라

public class <name-of-class> { 
// Class fields 
    <private|public|protected> [final] static .... 
// Object fields 
    private ... 
관련 문제