Java this keyword

Introduction

Java this keyword can refer to the current object.

The following code uses this.width to reference the instance variable width.

// A redundant use of this.
LegoBlock(double w, double h, double d) {
  this.width = w;
  this.height = h;
  this.depth = d;
}

Instance Variable Hiding

The following code uses this to resolve name-space collisions between method parameters and instance variables.

// Use this to resolve name-space collisions.
LegoBlock(double width, double height, double depth) {
  this.width = width;
  this.height = height;
  this.depth = depth;
}

Full source code

// LegoBlock uses a parameterized constructor to 
// initialize the dimensions of a lego block.
class LegoBlock {
  double width;//  w ww.  ja v a2s  .  c o  m
  double height;
  double depth;

  // This is the constructor for LegoBlock.
  LegoBlock(double w, double h, double d) {
    this.width = w;
    this.height = h;
    this.depth = d;
  }

  // compute and return volume
  double volume() {
    return width * height * depth;
  }
}
  
public class Main {
  public static void main(String args[]) {
    // declare, allocate, and initialize LegoBlock objects
    LegoBlock myLegoBlock1 = new LegoBlock(10, 20, 15);
    LegoBlock myLegoBlock2 = new LegoBlock(3, 6, 9);

    double vol;

    // get volume of first box
    vol = myLegoBlock1.volume();
    System.out.println("Volume is " + vol);

    // get volume of second box
    vol = myLegoBlock2.volume();
    System.out.println("Volume is " + vol);
  }
}



PreviousNext

Related