File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes about constructors Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "about constructors" Watch "about constructors" New topic

about constructors

Bhuvana Dhruva

Joined: Sep 11, 2000
Posts: 28
'To call a constructor in the superclass, you have to place the call as the first statement in the calling constructor' what does this mean? please illustrate with an example, it would be clearer.

Stephanie Grasson
Ranch Hand

Joined: Jun 14, 2000
Posts: 347
Here is an example:

Hope this helps.
Ling Wu
Ranch Hand

Joined: Jul 19, 2000
Posts: 184
Also, I think if the superclass constructor requires argument(s)you must provide them in this super() call.
Ruchi Gupta

Joined: Sep 09, 2000
Posts: 11
Actually in the sub class constructer we need to declare super()(so as to call super class constructor)when we are passing arguments in the constructor.
consider this example:
class base
System.out.println("from super");
class sub extends base
sub(int i)
System.out.println("from sub");
class testconstructor
public static void main(String asd[]){
sub s = new sub(23);}
here the output is:
from super
from sub
this shows that when we initalize the sub class then we don't explecitely make a call to the super class constructor then the default constructor is called by itself.
hence here i did not give super still it worked.
i hope this will help


Ruchi<br />_ _ ___________________________ _ <br />Tata Consultancy Services,<br />New Delhi, India
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
The reason why super is to be called first is as follows (I think)
When class B extends class A, the class B already all the elements of B. However B is free to change/add/modify these. So, any initialisation that is to be done should be done first, before it can be changed by class B. Hence the reason to call super()first.
Hope this helps
Good Luck.
PS: Its always useful to try and wonder why things are done in a particular way. The how of it comes automatically after that.
I agree. Here's the link:
subject: about constructors
It's not a secret anymore!