• Post Reply Bookmark Topic Watch Topic
  • New Topic

what is the usage of super() to invoke super class constructor!  RSS feed

 
krishnadhar Mellacheruvu
Ranch Hand
Posts: 118
Android Java Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi



when the above program is executed first SuperClass Constructor and then ChildClass constructor is (executed)displayed. What is the use of having the super keyword in the child class constructor when infact the super class constructor is executed when the object for the child class is created since the child class extends to the superclass.

Thanks
 
Stephan van Hulst
Saloon Keeper
Posts: 7969
143
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's no real use to call super(), because it's called implicitly whether you write it or not. Some people prefer to make it explicit, but it's unnecessary.

However, it *is* important to call super(...) at the start of the constructor if you want to invoke a superclass constructor that has parameters. Here's an example:
 
krishnadhar Mellacheruvu
Ranch Hand
Posts: 118
Android Java Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks stephan,

So unless we have to call the constructor which has got parameters it's ok not to use super keyword as this is implicitly called.. correct me if am wrong...
 
Stephan van Hulst
Saloon Keeper
Posts: 7969
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes that's correct.
 
Ganesh Patekar
Bartender
Posts: 726
23
Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
  • Let creation of an object of subclass invokes non-parameterized Or parameterized constructor of subclass, implicitly It invokes non-parameterized constructor of superclass by default. Sometime you may need to invoke a particular type of superclass's constructor rather than non-parameteried as given in Stephan's example then you can use super keyword.
  • That super keyword statement should always be first statement in constructor of subclass.
  •  
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!