2011-12-22 25 views
2

我若创建对象 而assing数据的阵列实施例后的...问题在对象阵列=所有元素都相同的...分配数据

短版本。 数组[0]的.init( “CE”,2) 阵列[1]的.init( “NH”,2)

输出...阵列的[0] 将是相同阵列[1] 但是为什么?怎么了?我需要..不一样的结果

下面是代码:

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
import java.util.*; 
import java.lang.Math; 


public class Gra_ulamki { 

    /** 
    * @param args the command line arguments 
    */ 

    public static ulamek[] tab_ulamkow; 
    public static void main(String[] args) 
    { 

     tab_ulamkow = new ulamek[30]; 


     tab_ulamkow[0] = new ulamek(); 
     tab_ulamkow[0].init("dd", 5); 

     tab_ulamkow[1] = new ulamek(); 
     tab_ulamkow[1].init("dde", 8); 

     System.out.println("poz x --" + tab_ulamkow[0].x + "-- y poz " + tab_ulamkow[0].y); 
      System.out.println("poz x --" + tab_ulamkow[1].x + "-- y poz " + tab_ulamkow[1].y); 

     // TODO code application logic here 
     //new GUI(); 
     //new GUI(); 
    } 

} 

class ulamek 
{ 
public static String ch_v; 
public static int x = 0, y = -5, y_max = 325; 


public void init(String a, int number) 
{ 
    this.ch_v = a; 

    // przypisanie x 
    this.x = number;  
} 


public void move() 
{ 


    // restart pozycji w osi y 
    if(this.y < y_max) 
    { 
     this.y += +1; 
    } 
    else 
    { 
     this.y = -5; 
    } 

} 

} 

谢谢大家帮忙

+0

'static'表示共享。 ;)最好不要在构造函数中设置静态字段。 – 2011-12-22 16:01:42

+0

你介意回答一个问题吗? – everton 2011-12-22 16:05:29

回答

6

如果数据成员是static,这意味着它是由类的所有实例共享:

public static String ch_v; 
public static int x = 0, y = -5, y_max = 325; 

删除两个static修饰符。

+0

谢谢!其作品 – 2011-12-22 15:59:52

2

ulamek类的栏目为static

这意味着,他们属于ulamek Type,而不是它的instances(对象)。

改变这样说:

class ulamek 
{ 
    public String ch_v; 
    public int x = 0, y = -5, y_max = 325; 
... 

,它应该工作。

2

ulamek类:

变化:

public static String ch_v; 
public static int x = 0, y = -5, y_max = 325; 

到:

public String ch_v; 
public int x = 0, y = -5, y_max = 325; 

声明的变量或方法静态意味着它的值是在所有类可用。

相关问题