Define your own objects in the class

In the C++ class definition, it is not possible to define objects of your own class in the class, but you can define pointer objects and references of your own class.

class A
{
    
    
public:
 A ()
 {
    
    
  cout<<"Constructor method."<<endl;
 };
 A a;
};
 
void main()
{
    
    
 A aa;
}

The above code compilation prompts an error

‘a’ : uses ‘A’,which is being defined。

If you can achange the achievement *a.

And java can define objects of its own class in the class.

class A{
    
    
  public A aa;
 }

Such code can be compiled smoothly, but if an object instance is created when it is defined, it will also fail to compile.

class A{
    
    
  public A aa = new A();
 }

Prompt error:

Exception in thread "main"java.lang.StackOverflowError at
test1$abc.(test1.java:4)

Obviously, the stack overflowed.
why? In fact, the essence of the above problems is the same, that is, the timing of creating object instances.
In C++, an instance of the object is created when the object is defined, that is, the memory space of the object is allocated. Therefore, if you define the object of your own class when you define it, it will lead to the phenomenon of recursively creating objects, creating object aa, because aa is an instance of class A, then there is an aa object in aa, and one must be created The aa object, allocate memory for it..., this will cause the object to be created recursively, and the result is that the memory is exhausted.
In Java, only by calling the new method can an instance of an object be created, and space for the object is allocated in memory. Objects can only create object instances when they are new, so objects of their own classes can be defined in a class. If the above example is modified to make an instance of a class, there will be no problems.

class A{
    
    
  public B bb = new B();
}

Such code can be compiled and run.
But if you use new to create your own object in a java class, it is possible to declare it as static. This is because the static member is initialized only once when the object of the class is created or the static member (method) of the class is called, and then it is not created and initialized again.

Guess you like

Origin blog.csdn.net/Fei20140908/article/details/108510334