Nomenclature question for finding information about combining classes

Hello!!
Is this called nested classes?

I need to know the correct name for placing a class within a class so I can search for reference materials.

For example, if I have 3 separate classes:
1st one = Grid class
2nd one = Shape class
3rd one = Color class

I want to find info on how to access the Shape class in the Grid class, etc

Thank you in advance!
:nerd_face:

It is called inner classes as far as I know.

Inner classes can’t have static elements and each instance is bound to a enclosing instance.
Processing handles it’s classes that way.

So if you create a new class in Processing it in reality creates a inner class of the sketches class.

Each element of a inner class can access the fields and methods of it’s enclosing instance. And vice versa.

Here is a little example:

class A {
  A() {
  }
  B createNewInstance() {
    return new B();
  }
  class B {
    private int somePrivateField=0;
    B() {
    }
    A getEnclosingInstance() {
      Object ret=null;
      try {
        java.lang.reflect.Field f=this.getClass().getDeclaredField("this$1");
        f.setAccessible(true);
        ret=f.get(this);
      }
      catch(Exception e) {
      }
      return (A) ret;
    }
  }
}
void setup() {
  A enclosingInstance=new A();
  A.B innerInstance=enclosingInstance.new B();
  println(innerInstance.somePrivateField);
  println(enclosingInstance,innerInstance.getEnclosingInstance());
}

2 Likes

you can also just write the 3 classes one after another separately:

class GridClass {
}

class ShapeClass {
}

class ColorClass {
}

and still have one class use the other; for example:

class GridClass {

    ArrayList<ShapeClass> list = ArrayList(); 
   
    void display(); 
        for(ShapeClass shape1 : list) {
            shape1.display(); 
        }
    }
}

class ShapeClass {

    ColorClass col = new ColorClass(); 
  
    void display() {
       fill(col.fillColor); 
    }

}

class ColorClass {
    color fillColor = color(222); 
    color strokeColor = color(111); 

}

etc.

3 Likes

Actually there’s a notable exception to that rule: :straight_ruler:

3 Likes

Hello @NumericPrime
Yes, I was wondering about inner classes. Though this looks a bit more complex than I had envisioned…
:face_with_open_eyes_and_hand_over_mouth:
But I definitely appreciate seeing this example for future use when I’m further along in my coding knowledge.
Thank you!!
:nerd_face:

@Chrisir !!
This makes sense. I think this is the direction I want to go.
Thank you!!
:nerd_face:

It took a little while but I finally got this to work!! Thank you again!!!
:nerd_face:

2 Likes