Remember to use the constructor:
1. the constructor must have the same name as the class. (If a source file contains multiple classes, the constructor must have the same name as the public class)
2. Each class can have more than one Constructor
3. the constructor can have 0, 1, or more parameters.
4. the constructor does not return values.
5. the constructor is always called along with the new operation.
Example:
A. java
Java code
- Public class {
- Public (){
- System. out. println ("calling constructors without Parameters ");
- }
- Public A (String mess ){
- System. out. println ("constructor with parameters \ n" +
- "Parameter content:" + mess );
- }
- }
Test. java
Java code
- Public class Test {
- Public static void main (String [] args ){
- A a_1 = new A (); // call A constructor without Parameters
- A a_2 = new A ("Hello"); // call A constructor with Parameters
- }
- }
Output result:
Inheritance and constructor
The statement for calling the parent class constructor Using Super must be the first statement of the subclass constructor.
If the subclass constructor does not explicitly call the constructor of the parent class, the default (No parameter) constructor of the parent class is automatically called. If the parent class does not have a constructor without parameters and the constructor of the Child class does not explicitly call the constructor of the parent class, the Java compiler reports an error.
Example:
A. java
Java code
- Public Class {
- Public (){
- System. Out. println ("calls a's no-argument constructor ");
- }
- Public A (string mess ){
- System. Out. println ("called a constructor with parameters \ n" +
- "Parameter content:" + mess );
- }
- }
B. java
Java code
- Public Class B extends {
- Public B (){
- System. out. println ("the no-argument constructor of B is called ");
- }
- Public B (String mess ){
- Super (mess );
- System. out. println ("the constructors with parameters of B \ n" +
- "Parameter content:" + mess );
- }
- }
Test. java
Java code
- Public class Test {
- Public static void main (String [] args ){
- B B _01 = new B ();
- B B _02 = new B ("hello ");
- }
- }
Output result: