Home > Net > In the parent class main method to create the parent class instance, and then create a grandson in s
In the parent class main method to create the parent class instance, and then create a grandson in s
Time:10-08
//the following two code, compile and run the error, will show that the Process is terminated due to StackOverflowException. //what reason be excuse me? I am familiar with such as stack memory is not enough, please master guiding
Class Program { The static void Main (string [] args) { A. A=new A (); Console. WriteLine (" Ok "); } } Class A: the Program { B B=new B (); } Class B: A {}
&
Class Program {
B B=new B (); The static void Main (string [] args) { A. A=new A (); Console. WriteLine (" Ok "); } } Class A: the Program {} Class B: A {}
CodePudding user response:
Class A { A, b=new A (). } This will trigger a stack overflow,
Because each to create A new instance, the instance initialization class member b, must be another A new instance, Thus layers of creating endlessly, until the stack overflow,
CodePudding user response:
For the first time see this application,
Is actually in the circulation, although is different instances, but has been created, you will not survive,
You can debug the see
CodePudding user response:
Because subclass initialization, must run in to the parent class constructor side first,
CodePudding user response:
subclass initialized first perform the superclass constructor, In fact you code 1 and code 2, is the same, There is no difference between nature,
Only one on new parent class A, B One on top of another top parent Program in new B New subclasses so as long as the parent class, but a subclass has inherited from the superclass, Got caught up in the subclass initialization time, first initialize the parent class, and then the parent class new subclasses, subclass continue to initialize the infinite loop,