how can I created method the all object in class do it in java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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()???

3rd Sep 2019, 2:58 AM
Khaled Abd Al-hamead Hawwas
Khaled Abd Al-hamead Hawwas - avatar
4 Answers
+ 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()
3rd Sep 2019, 6:44 AM
Trigger
Trigger - avatar
+ 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();
3rd Sep 2019, 9:50 AM
D_Stark
D_Stark - avatar
+ 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(); } }
3rd Sep 2019, 8:05 AM
zemiak
0
Is this Java?
3rd Sep 2019, 6:38 AM
Trigger
Trigger - avatar