Construction method with inheritance

Source: Internet
Author: User

1. The constructor method of the subclass must be called in the constructor method of its base class.

2. Subclasses can use Super (argument_list) to call the constructor of the base class in their own constructor method.

3. Use this (arguement_list) to invoke the other constructor methods of this class.

4. If you call the base class using Super (), the constructor method must be written in the first row of the subclass construction method.

5. If the constructor of the subclass is not displayed in the construction method of the child class, then the system automatically calls the constructor of the base class without parameters.

6. If the constructor of a subclass is not displayed in the constructor of the calling base class, and there is no constructor for the parameter in the base class, the compilation error occurs.

Class A {
protected void print (String s) {
System.out.println (s);
}
A () {
Print ("A ()");
}
public void F () {
Print ("A:f ()");
}
}
public class B extends a{
B () {
Print ("B ()");
}
public void F () {
Print ("B:f ()");
}
public static void Main (string[] args) {
b b = new B ();
B.f ();
}
}

The parser outputs the result, first new object B, which is the constructor of the call B. Since B inherits the Class A, B must inherit the constructor of a, and in the constructor of B there is no construction method using super (argument_list) called A, so system default B calls a constructor without parameters in a, and then outputs a (). Next, the construction method of B is executed, and the output B (). The last program calls B.F (), in B F () is overriding the F () in a, and the F () in a is overwritten, so the output is b:f ().

In conclusion, the output is:A ()

B ()

B:f ()

Construction method with inheritance (goto)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.