Subclass instantiation Process

Source: Internet
Author: User

First look at the code

Class person {int age; string name; person () {system. out. println ("no-argument constructor for person");} person (INT age, string name) {This. age = age; this. name = Name; system. out. println ("parameter constructor of person");} void eat () {system. out. println ("dinner ");}}

 

Class student extends person {int grade; student () {// super (); system is added by default. out. println ("Student's no-parameter constructor");} student (INT age, string name, int grade) {// This. age = age; it is the same as the code in the parent class. // This. name = Name; Super (age, name); // call the constructor of the parent class this. grade = Grade ;}}

 

class Test{      public static void main(String args[]){           Student s2 = new Student();            Student s1 = new Student(18,"zhangsan",3);      }}

In a subclass constructor, the constructor of the parent class must be called. If the constructor of the parent class is not explicitly called in the subclass constructor, the compiler automatically adds super (); call a specific parent class Constructor (similar to this) based on the parameters passed in the brackets ).

Why ??

The subclass inherits the member variables and member functions of the parent class, but cannot inherit the constructor. Repeated code is generated when assigning values to the member variables of the parent class in the constructor of the subclass. The super keyword is used to call the constructor of the parent class to solve this problem.

When super is used to call the constructor in the parent class, this line of code must be the first statement.

Subclass instantiation Process

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.