Can't acces class variables in function


#1

Hello,
before I start, I must say I’m pretty much a total newbie when it comes to programming in Processing, or in Java in general. As you can see, I have two shape classes, rectangle and circle. I’m trying to implement a function checkForNoOverlap , which takes and array of already drawn shapes, and a new shape, which we have to check against every other one, if it’s overlapping. I’ve tried to use two instanceof expressions, to cover cases when we would compare two circles, two rectangles or a rectangle and a circle. However, right at the beginning, I have a problem - when I try to access selected shape’s coordinates with object.rectX , it says "The global variable "rectX" does not exist." Why doesn’t it allow me to access it?

Thank you for you help,
Benjamin

Code:

Summary
class shape{
}

class rectangle extends shape{
  int stroke = 9;
  int rectX;
  int rectY;
  int rectWidth;
  int rectHeight;  
}
class circle extends shape{
  int stroke=9;
  int circleX;
  int circleY;
  int diameter;
}

ArrayList<shape> drawnShapes = new ArrayList<shape>();

boolean checkForNoOverlap(ArrayList<shape> drawnShapes, shape object){
  if (object instanceof rectangle){
    for (shape other: drawnShapes) {
      if (other instanceof rectangle){
        {
          if (Abs(object.rectX - other.rectX) > (object.rectWidth/2 + other.rectWidth/2)) {return true;} 
          if (Abs(object.rectY - other.rectY) > (object.rectHeight/2 + other.rectHeight/2)) {return true;}  
          return false;
          }
        }
      //if other object is circle...
    }
  }
  else{
    //if new object is circle....
  }
}

#2

Try initialising the rectX variable… or the shape objects in General.


#3

You need to cast object to the right class like this:

if (object instanceof rectangle) {
  rectangle rect = (rectangle) object;
  println(rect.rectX, rect.rectY); // use it through rect
}

I would advise to make first letter of you class names uppercase, like Rectangle or Shape, and keep variables lowercase. It keeps it clear what is a class and what is a variable and it is a convention which nearly all Java programmers adhere to.