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

can we call super() outside constructor?

 
Divyya Joshi
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey friends !
I want know Can we make a call to super class method using keyword "super . METHOD_NAME" from outside the constructor ?
I read it somewhere we can't call super(); outside the constructor .
Kindly clarify my doubt .
 
John Stark
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you can:



The output is:
In class A
In class B

You need this kind of call when you override a method and you want the method to do something in addition to the superclass method. So you say: "Do the stuff defined in the superclass and then something in addition.
If you just call super(); then this is a call of the superclass constructor and that can be only done from within a subclass constructor. Even more specific it has to be the first statement in the subclass constructor.


John
 
Ram Narayan.M
Ranch Hand
Posts: 247
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes definitely you can call

super.<method-name> (or) super.<field-name> from the instance methods and constructor... but not in static methods...

And super() can be called only in the constructor that too as the first statement...

The fact is super() is to indicate that the initialization of inherited super class properties should be initialized before the sub-class properties are initialized so it can be done only in the constructor...

In short,

super() (or) super(args) to invoke the super class constructor in first statement of sub-class constructor...

"super." keyword used to invoke super class methods (or) access super class variables that too in instance methods only
 
Matthew Brown
Bartender
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The best thing you can do, whenever you have a question "can I do ...", is to try it out. You'll remember it better that way, and it's both faster and more reliable than asking in a forum. What forums are good for is helping you understand why it works like that.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic