The Java constructor is a very important function, first of all, the constructor in Java can be overloaded, and because it can be inherited in the parent class constructor, so in the subclass, first of all must be called the constructor of the parent class. You can look at the following two examples to compare:
public class Test
{public
static void Main (String args[])
{
b = new B (m);
}
}
Class A
{public
a ()
{
System.out.println ("A without any parameter");
}
Public A (int i)
{
System.out.println ("A with a parameter");
}
Class B extends A
{public
B ()
{
System.out.println ("B without any parameter");
}
Public B (int i)
{
System.out.println ("B with a parameter");
}
The final output of this example is
A without any parameter
B with a parameter
You can see that the constructor of the parent class is called first, and then your own constructor is invoked. But because the constructor of a parameter in class B here does not have a super parent class, it causes it to execute only the constructor with no arguments for the parent class. If you want it to perform the constructor of a parent class with parameters, write the code like this:
public class Test
{public
static void Main (String args[])
{
b = new B (m);
}
}
Class A
{public
a ()
{
System.out.println ("A without any parameter");
}
Public A (int i)
{
System.out.println ("A with a parameter");
}
Class B extends A
{public
B ()
{
System.out.println ("B without any parameter");
}
Public B (int i)
{
super (i); Here is the parameterized constructor
System.out.println ("B with a parameter") inherited from the parent class;
So the final output is:
A with a parameter
B with a parameter
Therefore, the derived class must call the constructor of the parent class that contains the parameters through super. Here is another question:
public class Test extends X
{
y y = new Y ();
Test ()
{
System.out.print ("Z");
}
public static void Main (String args[])
{
new Test ();
}
}
Class X
{
y b = new Y ();
X ()
{
System.out.print ("x");
}
}
Class y
{
y ()
{
System.out.print ("Y");
}
}
What is the result of the output?
First, we will analyze this problem:
Because first look at this main function, this main function has only one code: the new Test (), because we found that the test class is inherited from X, so we first construct x, then we do the X class run Y B = new Y (), and then we can see the output y, Then it's the constructor for the X class, the output x, then the Y, then the test own constructor, the output z, so the output is yxyz.
The above about the Java constructor Some of the knowledge is small series to share all the content, hope to give you a reference, but also hope that we support cloud habitat community.