A Conversation for The H2G2 Programmers' Corner

Super() in JAVA, any thoughts?

Post 1

Terran

I was just wondering what "Super()" in Java, with reference to inheritence, is supposed to do. In the examples I've used I can't seem to see its purpose. Any thoughts?

Ste


Super() in JAVA, any thoughts?

Post 2

26199

It's used for calling the parent class's constructor with some argument, I think... it's only allowed at the very start of a constructor.

I believe there's always an implicit super() there anyway, i.e. the parent constructor is always called first. So its only use is if you want to call it with an argument instead.


Super() in JAVA, any thoughts?

Post 3

26199

In fact - I used it today. I was making a class that inherits from BufferedReader:

public NiceReader(InputStreamReader reader)
{
super(reader);
}

When this is called, the result is the same as that returned by BufferedReader(InputStreamReader reader), except with my additions.


Super() in JAVA, any thoughts?

Post 4

Terran

I think I've got an idea... but I'm still not really clear on it. One of the examples I've got in front of me starts with :-

public class Customer {

// Default Constructor
public Customer () {
super ();
}

.... etc and goes on to use StringBuffer to append a load of text together. But in this example I'm having difficulty trying to figure out why it is used. Does Super() actually need to be there?


Super() in JAVA, any thoughts?

Post 5

26199

Well, the super() is implicitly there anyway... since the class doesn't explicitly inherit from anything, it inherits from Object... I don't know whether Object does any initialisation of its own, but if it does, that's when it does it...

But, yeah, you could get rid of that one and it wouldn't make any difference.


Super() in JAVA, any thoughts?

Post 6

Terran

Thanks, I think I've got the gist of it now.


Super() in JAVA, any thoughts?

Post 7

Ausnahmsweise, wie üblich (Consistently inconsistent)

Yes - that's correct.
e.g.
In a class that extends UnicastRemoteObject you would write this..

public HelloImpl() throws RemoteException {
super();
}


It really isn't needed because the no argument default constructor is automatically called. But it documents for the reader that the call is made.And then the reader realizes why there are exceptions thrown (becasue the parent constructor can fail), etc.

Awu


Super() in JAVA, any thoughts?

Post 8

some bloke who tried to think of a short, catchy, pithy name and spent five sleepless nights trying but couldn't think of one

But the main use IS when you want to call a non-default constructor of the superclass (ie one with parameters)

* bloke's wearing a lovely radioactive atoll for the bikini competition. Vote for me at A781184 or I'll take it off (you don't want that to happen) *


Super() in JAVA, any thoughts?

Post 9

MaW

And very useful it is too.


Key: Complain about this post