1

I've been looking into the topic of creating instances of a class within its own definition. Something like this:

public class myClass
{
    public static myClass aObject = new myClass();
    public static myClass bObject = new myClass();
}

I kind-of understand how this is possible, but I'm confused as to why it would be useful.

Also, my logic says that it should be possible to do something like this:

aObject.bObject.someMethod();

aObject is an instance of myClass, so it should contain bObject, right? I feel like I'm missing some fundamental understanding of how classes work, so I would really like to know what's going on here, and why someone would want to do this.

4

2 回答 2

0

aObject.bObject.someMethod() would definitely work if someMethod() was defined as a part of myClass. As to why something like that would be done, I'll give an example that is used in java.

Say you have a class called Color that represents colors. You can make a new color of of its RGB value with the constructor Color(byte r, byte g, byte b). There are also constants in the Color class that represent commonly used colors, like red or green or pink. You can quickly access the pink color just by saying Color.PINK, since PINK is a Color variable that is inside the Color class. That way you don't have to construct a new color object each time you want to use pink in a method.

于 2012-08-21T02:33:34.073 回答
0
aObject.bObject.someMethod();

This is like saying "of object a's object b... do something." So its like a ball (called A) has a ball inside it (called B) which has a ball inside it (called C).. ect.

A linked list is a list does something like this, in that:

class Link {

public long data;                        // data item
public Link next;                        // next link in list
// =============================================================
    public Link(long value){             // constructor
        data = value;                    // assign parameter to data's data field   
    }
}

Link has inside of it a pointer to another link which does the same until you make a null object.

I think this is what you were asking...

于 2012-08-21T02:40:09.567 回答