Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

about constructors

 
Bhuvana Dhruva
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
'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.
thanks,
 
Stephanie Grasson
Ranch Hand
Posts: 347
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bhuvana,
Here is an example:

Hope this helps.
Stephanie
 
Ling Wu
Ranch Hand
Posts: 184
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, I think if the superclass constructor requires argument(s)you must provide them in this super() call.
 
Ruchi Gupta
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
{
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
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bhuvana,
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.
Ambi
PS: Its always useful to try and wonder why things are done in a particular way. The how of it comes automatically after that.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic