Programming Tutorials

(追記) (追記ここまで)

The this Keyword in Java

By: aathishankaran in Java Tutorials on 2007年03月03日 [フレーム]

In Java, the this keyword refers to the current instance of the class. It can be used to refer to instance variables or methods of the current object.

Here's an example using a Box class:

public class Box {
 private int length;
 private int width;
 private int height;
 
 public Box(int length, int width, int height) {
 this.length = length;
 this.width = width;
 this.height = height;
 }
 
 public int getVolume() {
 return this.length * this.width * this.height;
 }
}

In the Box class, the constructor takes three parameters: length, width, and height. Inside the constructor, this is used to refer to the current object, and the instance variables length, width, and height are initialized with the values passed as arguments.

The getVolume() method uses this to refer to the current object and the instance variables length, width, and height to calculate and return the volume of the box.

Overall, this is a useful keyword in Java that allows you to refer to the current instance of the class and access its instance variables and methods.




(追記) (追記ここまで)


Add Comment

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /