Java: Method of calling methods between subclasses and parent classes

Source: Internet
Author: User

Reviewing the Basics:

1. If a constructor is not defined in a class, the compiler automatically adds the default parameterless constructor at compile time

define the format: Public ClassName () {}

2. The difference between this and super.

3. Each class is directly or indirectly a subclass of object, and object has only one parameterless construction method.

4. The compiler implicitly adds the default parameterless constructor of the parent class to the first row of each construction method, adding super ().

Errors that are easy to make:

Class Family extends Object {

Public Family (int member) {

}

}

Class Father extends Family {

Public Father () {

}

}

The above code will generate a compilation error:

Implicit super constructor Family () is undefined. Must explicitly invoke another constructor

Because the parent class defines a constructor with parameters, the compiler does not add a default parameterless construction method.

However, because a constructor of the parent class is not explicitly called in the constructor of the subclass, the compiler automatically adds the super () method,

However, the default parameterless construction method does not exist in the parent class, so it is suggested that the default parameterless construction method does not define an error.

The Modified code:

Class Family extends Object {

Public Family (int member) {

}

}

Class Father extends Family {

Public Father () {

Super (6);

}

}


In this way, a constructor for the parent class is explicitly called in the constructor of the child class, so the super () method is not automatically added by the compiler.

Java: Method of calling methods between subclasses and parent classes

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.