Simple Java Question

Status
You're currently viewing only Sans's posts. Click here to go back to viewing the entire thread.
Not open for further replies.

Sans

Wise, Aged Ars Veteran
144
Originally posted by Ding:
Constructors can't have return types, and super() makes little sense outside of a constructor.
Or at least I've never seen super() outside of a constructor.

You'll see super() used occasionally outside constructors. Usually happens when you override a method in a class you're extending but still want the original parent method to be called. For example:

code:<HR>
Code:
public class MoreStuff extends Stuff
{
  // constructors and other misc.<P>  public void doStuff()
  {
    System.out.println("Doing more stuff!");<P>    // have to use super() since simply calling doStuff() again will
    // result in recursion w/o a stop condition<P>    // This would probably print "Do stuff!" or similar
    super().doStuff();
  }
}
 

Sans

Wise, Aged Ars Veteran
144
Try super not as a function call but as a attribute.

Oops. My fault. That's what I get for typing code in a web page :)

Here's an example snippet from a class I wrote to extend HashMap (I wanted to wrapper all objects I put in the map to store additional information for the object)

code:<HR>
Code:
public Object put(Object key, Object value)
{
  return(super.put( key, new ObjectWrapper(value, null, 0)));
}

Would like to claim credit for the idea, but actually found the idea in the article below. I just made a simplified version.
Javaworld Article
 
Status
You're currently viewing only Sans's posts. Click here to go back to viewing the entire thread.
Not open for further replies.