1. use of the keyword SUPER.
If your method overrides one of its superclass methods, you can invoke the overridden method with the super keyword. You can also use super to refer to a hidden field (although hiding fields is not recommended). Consider this class, Superclass:
public class Superclass { public void printMethod() { System.out.println("Printed in Superclass."); }
}
Here is a subclass of the Subclass subclass that overrides printMethod ():
public class Subclass extends Superclass {
}
Inside the subclass, the simple name printMethod () refers to a declaration in the subclass that overrides the value in the superclass. So, to reference printMethod () inherited from Superclass, Subclass must use a qualified name using super, as shown. Compiling and executing the subclass prints the following:
Printed in a superclass. Printed in a subclass.
2. using the THIS keyword Using this with a field
The most common reason for using this keyword is that the field is obscured by a method or constructor parameter.
For example, the Point class was written as follows:
public class Point { public int x = 0; public int y = 0;
}
but it could be written like this:
public class Point { public int x = 0; public int y = 0;
}
Each constructor argument obscures one of the object's fields - inside the constructor x there is a local copy of the first constructor argument. To access the Point x field, the constructor must use this.x.
Using this with the constructor
Inside the constructor, you can also use this keyword to call another constructor in the same class. This is called an explicit constructor call. Here is another Rectangle class, with a different implementation from the one in the "Objects" section.
public class Rectangle { private int x, y; private int width, height; public Rectangle() { this(0, 0, 0, 0); } public Rectangle(int width, int height) { this(0, 0, width, height); } public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; }
}
This class contains a set of constructors. Each constructor initializes some or all of the variables of the rectangle element. Constructors provide a default value for any member variable whose initial value is not provided by the argument. For example, a constructor with no arguments calls a constructor with four arguments with four values โโof 0, and a constructor with two arguments calls a constructor with four arguments with two values โโof 0. As before, the compiler determines which constructor should call based on the number and type of arguments.
If present, calling another constructor should be the first line in the constructor.