[英]How to Assign Elements in Class Array
I have a class named Tire
and it has a function.我有一个名为
Tire
的类,它有一个函数。 I call it in Car
class.我在
Car
课上称之为。 A car has 4 tires, so I need to declare the tires as an array in Car
class so I can call the function that is implemented in Tire
class.一辆汽车有 4 个轮胎,所以我需要在
Car
类中将轮胎声明为一个数组,以便我可以调用在Tire
类中实现的函数。 How exactly can I do it?我该怎么做?
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?
}
One option is to create a getter for it:一种选择是为它创建一个吸气剂:
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;
}
}
And in your main code:在你的主要代码中:
Tire t = car.getTire(3);
if (t != null) {
t.pumpAir(42);
}
Create a getter for the tires and access it using subscript as its private .为轮胎创建一个 getter 并使用下标作为其私有访问它。
Or change the access specifier to public and access it using subscript operator.或者将访问说明符更改为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?
}
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);
}
The best option is to create a getter in the Car class最好的选择是在 Car 类中创建一个 getter
public class Car
{
private Tire[] tires = new Tire[4];
public Tire[] getTires()
{
return tires;
}
}
Then in main, you can access the 3rd tire by然后在主要,您可以通过以下方式访问第三个轮胎
car.getTires()[2].pumpAir(someInt);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.