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