Initialization order of thinking in Java derived classes and base classes

Source: Internet
Author: User

In the thinking in Java, I changed the code slightly:

classreal{ PublicReal (String index) {//TODO auto-generated Constructor stubSystem.out.println ("Real ()" +index); }}classmeal{Real R=NewReal ("Meal"); Meal () {//TODO auto-generated Constructor stubSystem.out.println ("Meal ()"); }}classbread{Bread () {//TODO auto-generated Constructor stubSystem.out.println ("Bread ()"); }}classcheese{Cheese () {System.out.println ("Cheese ()"); }}classlettuce{lettuce () {//TODO auto-generated Constructor stubSystem.err.println ("Lettuce ()"); }}classLunchextendsmeal{Real R=NewReal ("Lunch"); Lunch () {System.out.println ("Lunch ()"); }}classPortablelunchextendslunch{Real R=NewReal ("Portablelunch"); Portablelunch () {System.out.println ("Portablelunch ()"); }} Public classSandwichextendsportablelunch{Bread b=NewBread (); Cheese C=NewCheese (); Lettuce L=Newlettuce (); Sandwich () {System.out.println ("Sandwich ()"); }     Public Static voidMain (string[] args) {//TODO auto-generated Method Stub        NewSandwich (); }}

Output


Real () Meal
Meal ()
Real () Lunch
Lunch ()
Real () Portablelunch
Portablelunch ()
Bread ()
Cheese ()

Lettuce ()
Sandwich ()

Summarize:

If both the derived class and the underlying class do not have static members, create the derived class, initialize the order: up, start with the root class, initialize the root class member, and then the root class constructor, then down, the second root class member, the secondary root class constructor, and so on, until the derived class itself.

Initialization order of thinking in Java derived classes and base 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.