Every time a subclass object is created with the New Keyword, the program will first execute the constructor without parameters in the parent class, and then execute the constructor of the subclass.
Every time a subclass object is created with the New Keyword, the program will first execute the constructor without parameters in the parent class, and then execute the constructor of the subclass.
Eg: I have created three classes: A parent class (a_constructor), a subclass (B _constructor), and a test class (test_constructor ). the code and running result are as follows:
Parent class:
Public class a_constructor {
Public a_constructor (){
System. Out. println ("the non-parametric Constructor ()" of the parent class ()");
}
Public a_constructor (int n ){
System. Out. println ("parent class constructor with parameters (n):" + n );
}
}
Subclass:
Public class B _constructor extends a_constructor {
Public B _constructor (){
System. Out. println ("subclass's non-parameter Constructor ()");
}
Public B _constructor (INT N ){
System. Out. println ("subclass Constructor (n) with parameters:" + n );
}}
Test class:
Public class test_constructor {
Public static void main (string ARGs []) {
B _constructor one = new B _constructor (); // without Parameters
B _constructor two = new B _constructor (2); // with Parameters
System. Out. println ("test ended ");
}
}
Running result:
The parameter-free Constructor () of the parent class ()
The non-parameter Constructor () of the subclass ()
The parameter-free Constructor () of the parent class ()
Subclass Constructor (n) with parameters: 2
Test ended
This article from: Development Institute http://edu.codepub.com Source: http://edu.codepub.com/2010/0108/19524.php