• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

super & this

 
Devaraj Rajakumar
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic