如何访问在main方法中创建的对象

时间:2014-11-08 21:50:23

标签: java object methods

我正在努力寻找如何通过另一种静态方法发送/访问在main方法中创建的对象。

这是我的一些服务类代码,它由公共构造函数,访问器和mutator方法组成:

  public class Participants 
    {
        String firstName=" ";
        String lastName=" ";
        int socialSecurity=0;
        int ticket=0;

        char status='N';
        Vehicle veh=null;


        public Participants(String fn, String ln, int ssn, int tkt)
        {
            firstName=fn;
            lastName=ln;
            socialSecurity=ssn;
            ticket=tkt;
        }
    }

还有Client类,它有我创建和初始化这些对象的主要方法,以及我试图访问这些对象的第二种方法:

public class Race
{
    public static void main(String[] args)
    {
        ....
        Participants []people=new Participants[35];
        Vehicle []cars=new Vehicle[10];
...code to "fill" those objects
        GiveAway([]cars,[]people); //sending those objects to static method- doesn't work from here)
    }

public static void GiveAway(Vehicle[] veh, Participants[] part)
    {
        //set of instructions to work and change those objects
    }
}

代码根本不起作用,这是因为我真的不知道如何将一个对象数组“发送”到一个方法(顺便说一下,这是可能的吗?)。

我是以正确的方式做到的吗?或者有一个更简单的方法?我找到了一些关于私人课程和其他所有课程的科目,但无法弄清楚如何处理我的代码。

我感谢任何帮助

谢谢!

3 个答案:

答案 0 :(得分:2)

我认为您认为阵列名称为[]people[]cars。不是。当你声明它们时,它实际上是:

Vehicle[]  cars = new Vehicle[10];
└───────┘  └──┘
  Type     var name

所以数组名为cars,那就是你应该如何将它传递给另一个方法:

GiveAway(cars, people);

作为旁注:不要给出以大写字母开头的方法名称。惯例是只有类型名称(类,接口等)以大写字母开头。常量是全大写的,方法的首字母小写。

答案 1 :(得分:1)

您对GiveAway的通话应如下所示

GiveAway(cars, people);

这些方括号会给你一个编译错误。

答案 2 :(得分:1)

 Participants []people=new Participants[35];
 Vehicle []cars=new Vehicle[10];
 GiveAway([]cars,[]people);

应该是

Participants[] people=new Participants[35];
Vehicle[] cars=new Vehicle[10];
GiveAway(cars, people);

在Java中,您使用[]向编译器发出信号,告知这是一个数组。你把它放在你要创建一个(参与者,车辆)数组的对象的名称后面。当调用“GiveAway”时,您只需要使用数组的名称。

相关问题