Home > Software engineering >  C # constructor calls to other constructors
C # constructor calls to other constructors

Time:11-20

C # a subclass constructor can be specified as the first call the other constructor (parent or sibling)
If not specified, the subclass constructor default first call no arguments constructor of the parent
For example,
Public (B)//the default first call no arguments constructor of the parent
Public (B) : the base (16)//B a no-parameter constructor, first call the superclass constructor with an int parameters
Public (B) : this (" string ")//B a no-parameter constructor, first call at the same level with a string argument constructor

//the console program
//the following code under the VS2010 debugging through
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. The Text;

The namespace test1

{
Class A//define A class A
{
The public (A)
{
Console. WriteLine (" I am A, no arguments constructor ");
}
The public A (int I)
{
Console. WriteLine (" I am A int constructor ");
}
The public A (String s)
{
Console. WriteLine (" I am A String constructor ");
}
}

Class B: A//class from class inheritance
{
Public (B) : the base (16)//first calls the superclass constructor, from parameter analysis, we should call A (int I)
{
Console. WriteLine (" I am a B, no arguments constructor ");
}
Public B (int I) : this (" string ")//first call the constructor, at the same level from the parameter analysis, should call B (string s)
{
Console. WriteLine (" I am B int constructor ");
}
The public B (String s)
{
Console. WriteLine (" I am B String constructor ");
}
}

Class Program
{
The static void Main (string [] args)
{
A a1=new A ();
Console. WriteLine (" \ n ");
A a2=new A (12);
Console. WriteLine (" \ n ");
A a3=new A (" string ");
Console. WriteLine (" \ n -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - \ n ");
B=new b1 (B);
Console. WriteLine (" \ n ");
B2 B=new B (" string ");
Console. WriteLine (" \ n ");
B3 B=new B (12);
The Console. The Read ();
}
}
}
The following for program output:
I am A, no arguments constructor


I am A int constructor


I am A String constructor

-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

I am A int constructor
I am a B, no arguments constructor


I am A, no arguments constructor
I'm B String constructor
I'm B int constructor


I am A, no arguments constructor
I'm B String constructor
*/

  • Related