This week's book giveaway is in the JavaScript forum.
We're giving away four copies of JavaScript Promises Essentials and have Rami Sarieddine on-line!
See this thread for details.
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


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "super & this" Watch "super & this" New topic
Author

super & this

Devaraj Rajakumar
Greenhorn

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: 2367
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
Sheriff

Joined: Oct 13, 2005
Posts: 39773
    
  28
This:

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);".

Super:

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: http://aspose.com/file-tools
 
subject: super & this