如何在类数组中分配元素

时间:2017-01-22 20:56:35

标签: java arrays

我有一个名为Tire的类,它有一个函数。我在Car课程中称呼它。一辆车有4个轮胎,所以我需要在Car类中将轮胎声明为一个数组,这样我就可以调用Tire类中实现的功能。我该怎么办呢?

class Tire {
    public void pumpAir(int psi) {}
}

public class Car {
    private Tire[] tires = new Tire[4];
}

public static void main(String[] args) {

    Car car = new Car();

    car.tires ... // how to call 3rd tire and pump it?
}

4 个答案:

答案 0 :(得分:0)

一种选择是为它创建一个getter:

public class Car {
    private Tire[] tires = new Tire[4];

    public Tire getTire(int i) {
        if (i >= 0 && i < tires.length) {
           return tires[i];
        }
        return null;
    }
}

在您的主要代码中:

Tire t = car.getTire(3);
if (t != null) {
   t.pumpAir(42);
}

答案 1 :(得分:0)

为轮胎创建一个getter,并使用下标作为 private 来访问它。
或者将访问说明符更改为 public 并使用下标运算符访问它。

public class Car {
    private Tire[] tires = new Tire[4];

    public Tire getTire(int number) {
         if(number >= 0 && number < tires.length) {
              return tires[number];
         } else {
              return null;
         }
    }

}

public static void main(String[] args) {

    Car car = new Car();

    car.getTire(2) ... // how to call 3rd tire and pump it?
}

答案 2 :(得分:0)

 public class Tire 
    {
        public void pumpAir(int psi) {
                 System.out.println("Tire number " + psi + " pumped.");
         }
    }



 public class Car {
        private Tire[] tires = new Tire[4];



 public Car()
    {
     for(int i=0;i<4;i++)
         this.tires[i]=new Tire(); 
    }

public Tire[] getTiers()

   {
     return tires;
   }
}

public static void main(String[] args) {



 Car car = new Car();

// how to call 3rd tire and pump it?
car.getTiers()[2].pumpAir(2 + 1);

}

答案 3 :(得分:-1)

最好的选择是在Car类中创建一个getter

--params.Login.username="abc"

然后在main中,您可以通过

访问第3轮胎
public class Car 
{
    private Tire[] tires = new Tire[4];

    public Tire[] getTires() 
    {
        return tires;
    }
}