【问题标题】:In Object Array = all elements are same... After assign data在对象数组中=所有元素都相同...分配数据后
【发布时间】:2012-01-26 05:51:13
【问题描述】:

例如,如果我创建对象数组 并评估数据...

问题的简短版本。 数组[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;
    }

}

}

感谢您的帮助

【问题讨论】:

  • static 表示共享。 ;) 最好不要在构造函数中设置静态字段。
  • 你介意回答吗?

标签: java arrays object


【解决方案1】:

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

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

删除两个static 修饰符。

【讨论】:

    【解决方案2】:

    ulamek 类中的字段是 static's

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

    这样修改:

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

    它应该可以工作。

    【讨论】:

      【解决方案3】:

      在课堂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;
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多