Why another Instance of the class?

I am new to processing and java as well. I've been following some tutorials to generate a bouncy ball sketch.

            import java.util.*;

            ArrayList balti = new ArrayList();



            void setup() {
              size(600, 600);
              smooth();



              for ( int i=0; i<100; i++) {
                Aloo keshavball = new Aloo(random(0, width), random(0, 200));
                balti.add(keshavball);
              }
            }

            void draw() {
              background(0);
              for (int i=0; i<100; i++) {
                Aloo keshavball = (Aloo) balti.get(i); // I want to focus here !! What is happening here? I am really confused ! 
                keshavball.mainfunction();
              }
            }

and other file is:

        class Aloo {

          float x;
          float y;
          float speedX=random(-5,5);
          float speedY=random(-5,5);

          Aloo(float _x, float _y) {

            x = _x;
            y = _y;
          }

          void mainfunction() {
            display();
            move();
            bounce();
            gravity();
          }
          void display() {
            ellipse(x, y, 20, 20);
          }

          void move() {
            x += speedX;
            y += speedY;
          }

          void bounce() {
            if (x > width) {
              speedX *= -1;
            }
            if (y > height) {
              speedY *= -1;
            }
            if (x < 0) {
              speedX *= -1;
            }
            if (y < 0) {
              speedY *= -1;
            }
          }

          void gravity() {
            speedY = speedY +0.25;
          }
        }
Tagged:

Answers

  • edited June 2017 Answer ✓

    Good question!

    An ArrayList stores a variable number of objects. This is similar to making an array of objects, but with an ArrayList, items can be easily added and removed from the ArrayList and it is resized dynamically.

    In your question the ArrayList doesn't know which type of objects it holds. Therefore in the line Aloo keshavball = (Aloo) balti.get(i); we have to "cast" the object to the type Aloo.

    • first step: balti.get(i) returns an object of an unknown type

    • 2nd step: (Aloo) "casts" this object to Aloo, which means we tell processing that the unknown object is in fact of type / class Aloo

    • 3rd step: with = we move this object that now has the type Aloo to an object keshavball of type Aloo

    keshavball is then only temporarily used to start the method mainfunction().

    Outdated

    This approach is outdated, since nowadays you can tell the ArrayList which type of Objects it holds in the first place, so we don't need to cast anymore.

    See

    https://www.processing.org/reference/ArrayList.html

  • Thank you so much Chrisir!

Sign In or Register to comment.