+ 1
how can I created method the all object in class do it in java
example class cars{ int x =0 move(){ x++ { } cars car1 = new cars cars car2 = new cars cars car3 = new cars i want all object move()???
4 Respostas
+ 1
If so then I think you want to use a constructor. The constructor will be called when each object is made
class Car
{
public static int count;
public Car()
{
count++;
}
}
Car car1 = new Car();
Car car2 = new Car();
Car car3 = new Car();
// at this point Car.count would be 3
If you want all cars to use the move() method, you should make it static so you can call it like this
cars.move()
+ 2
If you want all those cars to move exactly the same time make that int x=0; ➡️ static int x=0; doing this means that the variable belongs to the class rather then the instance so everytime one of your objects call this move method it will affect all your car objects.
to call a method on your object use the following
car1.move();
+ 1
// very early version
class Car {
int x=0;
void move() { x++; }
}
class Cars {
Car car1, car2, car3;
Cars(){
car1=new Car(); car2=new Car(); car3=new Car();
}
void moveAll(){
car1.move(); car2.move(); car3.move();
}
public static void main(String[] args) {
Cars cars = new Cars();
cars.moveAll();
}
}
0
Is this Java?