debxyz
1
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!
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
Chrisir
3
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:
3 Likes
debxyz
5
Hello @NumericPrime
Yes, I was wondering about inner classes. Though this looks a bit more complex than I had envisioned…
But I definitely appreciate seeing this example for future use when I’m further along in my coding knowledge.
Thank you!!
debxyz
6
@Chrisir !!
This makes sense. I think this is the direction I want to go.
Thank you!!
debxyz
7
It took a little while but I finally got this to work!! Thank you again!!!
2 Likes