[英]How to assign array elements to private variable and use them in another class?
[英]How to Assign Elements in Class Array
我有一個名為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?
}
一種選擇是為它創建一個吸氣劑:
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);
}
為輪胎創建一個 getter 並使用下標作為其私有訪問它。
或者將訪問說明符更改為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);
}
最好的選擇是在 Car 類中創建一個 getter
public class Car
{
private Tire[] tires = new Tire[4];
public Tire[] getTires()
{
return tires;
}
}
然后在主要,您可以通過以下方式訪問第三個輪胎
car.getTires()[2].pumpAir(someInt);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.