You need to remember when using the constructor:
1. The constructor must have the same name as the class (if there are multiple classes in a source file, 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, one, or more than 1 parameters
4. The constructor has no return value
5. The constructor is always called with the new operation
Example:
A.java
Java code
- public class a{
- Public A () {
- System.out.println ("Call a parameterless constructor");
- }
- Public A (String mess) {
- System.out.println ("Call a constructor with a parameter \ n" +
- "The parameter content is:" +mess);
- }
- }
Test.java
Java code
- public class test{
- public static void Main (String [] args) {
- A a_1=new a ();//Call an argument-free constructor
- A a_2=new A ("Hello");//Call a constructor with a parameter
- }
- }
Output Result:
Call the parameterless constructor
The parameter constructor is called
The parameter content is: Hello
Inheritance and constructors
The statement that uses super to call the parent class constructor 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 for the parent class is called automatically. If the parent class does not have a constructor with no arguments, and the constructor of the parent class is not explicitly called in the constructor of the subclass, the Java compiler will report an error
Example:
A.java
Java code
- public class a{
- Public A () {
- System.out.println ("a parameterless constructor called");
- }
- Public A (String mess) {
- System.out.println ("The argument constructor of a was called \ n" +
- "The parameter content is:" +mess);
- }
- }
B.java
Java code
- public class B extends a{
- Public B () {
- SYSTEM.OUT.PRINTLN ("No parameter constructor called B");
- }
- Public B (String mess) {
- Super (mess);
- SYSTEM.OUT.PRINTLN ("The parameter constructor for B is called \ n" +
- "The parameter content is:" +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:
The parameterless constructor of a was called
The parameterless constructor for B was called
A parameter constructor for a was called
The parameter content is: Hello
A parameter constructor for B is called
The parameter content is: Hello
Summary of usage methods for Java constructors (inheritance and constructors)