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