-1

In definition of generic Class add() method(shown below code) ,what is this.t doing. i mean what is " this " term here ? we didn't define any constructor name called this anywhere right ? is this predefined object ?

public  class Box<T> {
    private T t;

    public void add(T t) {
        this.t = t; // what is " this " term here ?
    }

    public T get() {
        return t;
    }

    public static void main(String[] args) {

        Box<Integer> integerBox = new Box<Integer>();
        Box<String> stringBox = new Box<String>();

        integerBox.add(new Integer(10));
        stringBox.add(new String("Hello World"));

        System.out.printf("Integer Value :%d\n\n", integerBox.get());
        System.out.printf("String Value :%s\n", stringBox.get());
    }
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
læran91
  • 283
  • 1
  • 15
  • There are `this` constructors, but it refers to the current `Box` instance here. – Elliott Frisch Dec 30 '15 at 03:02
  • `this` refeers to the instance of the object, and since the parameter is `t`, and the property of the class is also `t`, using `this` you can differenciate which is which – saljuama Dec 30 '15 at 03:04
  • http://stackoverflow.com/questions/2411270/when-should-i-use-this-in-a-class – Pshemo Dec 30 '15 at 03:09

1 Answers1

1
public  class Box<T> {
    private T t;

    public void add(T t) {
        this.t = t; // what is " this " term here ?
    }

The this.t is refering to the current Box instance(whitch is the actual private variable). Basically thats a setter. You can read more about setters here. Hope this helped!