I have a mostly theoretical question about objects that have objects (or contain an ArrayList of objects). Inside the nested objects, there’s no ‘built in’ way of getting to the original object, right? I can solve this by sending IDs or so, but I don’t quite get why there’s no cleaner way to do it. Example:
class Apple{
String description="apple";
Apple(){
}
void saySomething(){
println("I'm an", description, "and I live in a", [some sort of reference to the thing that 'own' me].description );
}
}
class Tree{
Apple a;
String description="tree";
Tree(){
this.a = new Apple();
}
}
This code won’t run, it’s just to illustrate the feature I keep feeling is missing. What am I missing? Shouldn’t this sort of referencing be possible? Why can I say “The apple that is in this tree”, but not “The tree this apple is in”?
A bunch of neat stuff here that’s new to me, thanks! It’s prettier than how I knew how to do similar, for sure. But it is still you telling the apple what it belongs to, with several lines and declarations, where I would assume that the info being sent to the apple, should be there under the hood somehow. I was curious if there was a hard reason for having to do it ‘manually’. Or is it just convention, or that no one thought it was worth the effort?
A “parent” of any object is the class which instantiates it.
An object is by itself a reference to the 1st memory address of its memory block.
When we assign an object to a variable (be it a field, parameter or an array’s index slot) we’re actually assigning the object’s memory address value to it.
An object’s reference isn’t self-aware whether its memory address value is being stored in 1 or more variables.
The JVM’s garbage collector (GC) would be the only entity knowing such info.
I see! Wonderful answer, thanks a lot! Without knowing this, it’s easy as a noob to feel like ‘well, this object knows, so the info must be there somewhere.’, when you don’t know the under the hood stuff.
you can give Apple a Constructor that enforces to put in a pointer to the tree, who created the apple. Then you can ask any Apple anytime about who is his tree. That is should be done quickly and easy.
Or a list, for that matter. Keep in mind that you aren’t limited to containment – you can have one-one, one-many, many-one, or many-many relationships. Also, the method for registering that relationship can be through the constructor or through a method on either object if it is passed the other object as an argument.
class Event {
ArrayList<Person> attendees;'
attend(Person p) {
attendees.add(p);
}
}
class Person {
attend(Event i) {
i.attendees.add(this);
}
}