if you instantiate subclass constructor will run after super class constructor. so super is used to call super class constructor so it should first line.. more over this is used to overload the constructor so it should first line of constructor.

you can use super anywhere inside a method

hope this helps

Campbell Ritchie

Marshal

Posts: 56546

172

posted 9 years ago

Not quite "this" or "super", but actually "this()" or "super()".

Thomas Thevis

Ranch Hand

Posts: 87

posted 9 years ago

Since all super types of your class might have internal fields, they have to have one of their constructors run. These super constructor runs have to be completed before your first assignment within your constructor. This makes perfectly sense. Suppose you could place the super() call anywhere within your constructor and a super type had protected member variables which are to be initialized in the super() call. If you would assign values in your constructor and afterwards call super(), your values vould be overridden. Fortunately, these kinds of errors cannot happen. The first call from a constructor is always a call to a this or a super constructor. If the super type has an accessible no-arg constructor this call can be performed implicitly for you. In this case, you don't have to call super explicitly.

SCJP 5.0, SCJD in progress

Thomas Thevis

Ranch Hand

Posts: 87

posted 9 years ago

Onother example of what would go wrong if calling super() was to be permitted everywhere: It is possible to declare a field final and assign a value in the constructor. In fact, the value then has to be assigned within the constructor. Suppose such a field would be acceesible for an extending class which was allowed to put its super() call anywhere in its constructor...

SCJP 5.0, SCJD in progress

James Basller

Ranch Hand

Posts: 58

posted 9 years ago

Originally posted by abin joy: a call to this or super should be the first line of any constructor if we are providing them?Why cant we have them anywhere in our constructor code?

yes, this() and super() both must be called from the first line of the subclass constructor. Object class is a super class of all the classes. So, if one is not defined constructor in the superclass compiler will automatically put super() call in the constructor. Because constructor chaining follows the order of topdown approach. So, one has must call super class constructor from the sub class constructor.