Java4android (subclass instantiation process in inheritance)

Source: Internet
Author: User

Subclass Generation Process

See the Code:

Class Person {String name; int age; Person () {System. out. print ("no-argument constructor of Person");} Person (String name, int age) {this. name = name; this. age = age; System. out. print ("constructor with two parameters for Person");} void eat () {System. out. print ("dinner ");}}

 

Class Student extends Person {int grade; Student () {// In the constructor of the subclass, the constructor of the parent class must be called. // If the constructor of the parent class is not written, then the compiler automatically adds super (); // super (calls the corresponding constructor in the parent class according to the parameter); System. out. print ("Student's no-parameter constructor");} Student (String name, int age, int grade) {// this. name = name; // this. age = age; super (name, age); // reduce repeated code this. grade = grade ;}}
class Text{    public static void main(String args[]){        Student s = new Student("zhansan",18,90);        System.out.print(s.name);        System.out.print(s.age);        System.out.print(s.grade);    }}

 

How to use super to call the parent class Constructor

Because the subclass inherits the member variables and member functions of the parent class, but cannot inherit the constructor of the parent class, the code will be repeated when assigning values to the member variables. To solve this problem, use super to call the constructor of the parent class ..

Note: super must be in the first line of the constructor.

 

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.