Differences in the execution process of Java and CSharp class inheritance:
Java execution: Subclasses first initializes the members of the parent class → Initializes the parent class's constructor → Returns the child class executes the member of the initialization subclass → Initializes the subclass constructor.
CSharp Execution: Subclasses initialize the members of the subclass → Initialize the members of the parent class → Initialize the constructor of the parent class → Initialize the constructor of the subclass.
Assume that Class A inherits from Class B.
Java execution process: Class A initializes the members of Class B → Initializes the class B constructor → Initializes the Class A member → Initializes the Class A constructor.
CSharp Execution Process: Class A initializes the members of Class A → Initializes the members of Class B → Initializes the class B constructor → Initializes the class A constructors.
Assume: Class A inherits from Class B, Class B inherits from Class C, and so on.
Java execution: Class A initializes the members of Class C → Initializes the class C constructor → Initializes the member of Class B → Initializes the class B constructor → Initializes the Class A member → Initializes the Class A constructor.
CSharp Execution Process: Class A initializes the members of Class A first → Initializes members of class B → Initializes members of class C → Initializes the class C constructor → Initializes the class B constructor → Initializes the class A constructor.
Example code:
----------------------Java Code----------------------
1 //----------------------Java code----------------------2 classDemoextendsx{3Y y =NewY ();4Demo () {System.out.print ("Z"));}5 Public Static voidMain (string[] args) {6 NewDemo ();7 }8 }9 classXextendsJ {TenY y =NewY (); One X () { ASystem.out.print ("X"); - } - } the classY { - Y () { -System.out.print ("Y"); - } + } - classj{ +K k =NewK (); A J () { atSystem.out.print ("J"); - } - } - classk{ - K () { -System.out.print ("K"); in } - } to //The result of Java output is: kjyxyz
----------------------CSharp Code----------------------
1 //----------------------CSharp Code----------------------2 usingSystem;3 4 classdemo:x5 {6Y y =NewY ();7 8 PublicDemo ()9 {TenConsole.Write ("Z"); One } A - Static voidMain (string[] args) { - NewDemo (); the } - } - - Public classx:j + { -Y y =NewY (); + PublicX () A { atConsole.Write ("X"); - } - } - - Public classY - { in PublicY () - { toConsole.Write ("Y"); + } - } the * Public classJ $ {Panax NotoginsengK k =NewK (); - PublicJ () the { +Console.Write ("J"); A } the } + - Public classK $ { $ PublicK () - { -Console.Write ("K"); the } - }Wuyi //csharp Output Result: Yykjxz
Differences in the execution process of class inheritance for Java and CSharp