File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes super & this Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "super & this" Watch "super & this" New topic

super & this

Devaraj Rajakumar

Joined: Apr 16, 2007
Posts: 6
Hi,Today I came across the keyword �super� and �this�. What I understood from the book was that �super� can retrieve the immediate superclass�s value and �this� used for object�s class value.

Can someone please explain with a real/simple example of the usage of �super� & �this� keyword.

Thank you
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
super can be used in a subclass to call an immediate superclass's constructor, and also to call the original version of an overridden method.

this can be used to overcome shadowing.

Consider this example.

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46340

The present object. Not quite class value, but the object itself.

You can distinguish local variables (or parameters) from fields of the same name by prefixing the field's identifier with this. Example of constructor for a clock, which is similar to an example in Deitel and Deitel's book, and I have copied and pasted from a posting I wrote yesterday:
The parameters hour minute second are distinguished from the fields of the same name because the fields have this.hour in.

Same snippet: note the constructor is overloaded; there are actually 4 constructors here, and you can call a constructor from another constructor by writing "this(something);". Note such a constructor call has to be the first line of the constructor.

You can send "this" as an argument to a method. If you set up an ObjectOutputStream for serialising, you can call "oos.writeObject(this);".


The keyword super refers to the immediate superclass, as you correctly said.
If your superclass doesn't have an accessible no-argument constructor (or a default constructor added by the compiler), you must call the superclass' constructor with a "super(something);" call. The super call must be the first line in a constructor, so you can't use super() and this() in the same constructor, but you can use this() to lead control to a constructor with super() in.
You can also call a superclass' method (if it is accessible) from anywhere in the subclass by writing . . . super.someMethod(something) . . . This call does not have to be the first line.
I agree. Here's the link:
subject: super & this
It's not a secret anymore!