Why is my Constructor Producing the Wrong Results

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hari krishnan
    New Member
    • Jun 2011
    • 5

    Why is my Constructor Producing the Wrong Results

    This is my code

    Code:
    class Atom {
    Atom() { System.out.print("atom "); }
    }
    class Rock extends Atom {
    Rock(String type) { System.out.print(type); }
    }
    public class Mountain extends Rock {
    Mountain() {
    super("granite ");
    new Rock("granite ");
    }
    public static void main(String[] a) { new Mountain(); }
    }

    in my assumption , when the code reach line 12 its checks default constructor in mountain class its not found then go to the parent class rock then go to the parent of the rock atom and print "atom" . then come to next line 13.calls single parameter of the super rock class.will print "granite".
    then again they create memory of the class with single
    parameter constructor , then print "granite".


    o/p should be in atom granite granite

    but here out put is like atom granite atom granite .

    how second time atom has came.
    Last edited by Niheel; Jul 9 '11, 06:57 PM.
  • plsHelpMe
    New Member
    • Jan 2008
    • 58

    #2
    In java, compiler by default put a no argument super call in the constructor of the subclass. So for your example code the sequence would be:

    1. line 16 calls no-arg constructor of Mountain class which in turn calls " super("granite ");" i.e. Rock class constructor, now as i said the compiler will call no argument constructor of the Atom class. This will print "atom"

    2. Control will come back to Rock class constructor and print "granite"

    3. Control comes to line#14 and calls "new Rock("granite ")" which in turn will call the no arg constructor of ATOM class and print"Atom"

    4. Rock class constructor prints granite.

    Final output; atom granite atom granite

    Comment

    • hari krishnan
      New Member
      • Jun 2011
      • 5

      #3
      hi friend, if the class doesnt contain constructor then it will create
      classname{super ();} .. but here the class already have argument constructor in atom class. then how compiler will create .

      Comment

      Working...