简体   繁体   中英

How to Assign Elements in Class Array

I have a class named Tire and it has a function. I call it in Car class. 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. 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 .
Or change the access specifier to public and access it using subscript operator.

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM