How to Add Buttons and Text to Your JavaFX Project
Advice for New Software Developers
How to Use the ShapeMaker Program in Java

How to Use this and super Keywords in Your Java Subclasses

The this keyword provides a way to refer to the current object instance in Java. It’s often used to distinguish between a local variable or a parameter and a class field with the same name. For example:

public class Ball
{
 private int velocity;
 public void setVelocity(int velocity)
 {
  this.velocity = velocity;
 }
}

Here the this keyword indicates that the velocity variable referred to on the left side of the assignment statement is the class field named velocity, not the parameter with the same name.

But what if you need to refer to a field or method that belongs to a base class? To do that, you use the super keyword. It works similarly to this but refers to the instance of the base class rather than the instance of the current class.

Consider these two classes:

public class Ball
{
 public void hit()
 {
  System.out.println("You hit it a mile!");
 }
}
class BaseBall extends Ball
{
 public void hit()
 {
  System.out.println("You tore the cover off!");
  super.hit();
 }
}

Here the hit method in the BaseBall class calls the hit method of its base class object. Thus, if you call the hit method of a BaseBall object, the following two lines are displayed on the console:

You tore the cover off!
You hit it a mile!

You can also use the super keyword in the constructor of a subclass to explicitly call a constructor of the superclass.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Java Programming: Add, Animate, and Light Up Objects in 3D
How to Set Up the Android SDK
Java: Negation, Bitwise Not, and Boolean Not
Programming Java: Looking for Files
Programming Java: Operator Precedence
Advertisement

Inside Dummies.com