Using this and super in Your Sub classes - Java Object Oriented Design

Java examples for Object Oriented Design:Inheritance

Introduction

this keyword refers to the current object instance.

this is 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;
      }
}

super keyword refers to the instance of the base class rather than the instance of the current class.

For example,

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();
      }
}

Related Tutorials