05.0 Java Notes‎ > ‎

Java: this. and super.

this.

When java has a choice of two variables with the same name, it will alway use the variable defined within the context of the method.   Adding this. before a variable forces Java to use the instance variable instead of the variable within the current scope of the program.

This allows one use of a variable as a parameter,  the other as an instance variable of the class (aka an attribute).  After all good variable names are hard to find.

super.

When creating classes based on inheritance, the sub-class inherits methods from it's parent.  The sub-class can contain a method with the same name that is contained in the parent, this is method overriding.  "super.methodname() is used to force Java to use the method from the parent, not the method from the class. "this.methodname()" explicitly state that the sub-class method is called.

super. can also be used with instance variables  <-- needs to be verified


Comments