2015-12-30 74 views
-1

定义通用类add()方法(下面显示的代码),this.t在做什么。我的意思是什么是“this”这个术语?我们没有在任何地方定义任何名称为this的构造函数名称?这是预定义的对象吗?通用类方法中的THIS这个术语的含义?

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

有'this'构造函数,但它指的是当前'Box'实例这里。 –

+0

'this' refeers对象的实例,因为参数是't',类的属性也是使用'this'可以differenciate哪个是哪个 – saljuama

+0

HTTP't',://计算器。 com/questions/2411270/when-should-i-use-this-in-a-class – Pshemo

回答

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

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

this.t是指的当前Box实例(whitch是实际的私有变量)。基本上这是一个二传手。你可以阅读更多关于制片人here。希望这有助于!