Java Course Assignment 06

Source: Internet
Author: User

Question one:

Why do I have to call the construction method of the parent class before the constructor of the subclass is run? Can you turn around? Why can't it be reversed?

Constructors are primarily used to allocate space for objects and initialize them.

Constructs an object that first calls its constructor method to initialize its member functions and member variables.

A subclass has member variables and member methods of the parent, and if not called, the member variables and member methods inherited from the parent class are not properly initialized.

Question two:

Write your own code to test the following features: In subclasses, to invoke methods overridden in a parent class, you can use the Super keyword.
1 classbase{2 3        protected Doublesize;4 5         PublicBase () {6size=0; System.out.println ("base class non-parametric construction");7        }8         PublicBase (Doubles) {9Size=s; System.out.println ("base class with reference structure");Ten        } One } A  -  Public classSubextendsbase{ -  the             PrivateString color; -  -              PublicSub () { -  +Color= "Blue"; System.out.println ("Sub class non-parametric construction"); -  +             } A  at              PublicSub (String c) { -  -Color=c; System.out.println ("Sub class has a parameter structure"); -  -             } -  in              -              PublicSub (Doubles,string c) { to  +                 Super(s);//calling a constructor with a parameter in the base class -  theColor=C; *  $System.out.println ("Sub class has a parameter structure");Panax Notoginseng             } -              the              Public Static voidMain (string[] args) { +Sub s1=NewSub (); ASub s2=NewSub ("Red"); theSub s3=NewSub (0, "red"); +             } - } $  $ //to explicitly invoke the constructor of a direct parent class with parameters in a subclass, you can do so through a super () call.  -  -          

Java Course Assignment 06

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.