Javathis变量总结

来源:计算机等级考试    发布时间:2012-08-29    计算机等级考试视频    评论

  this为一系统资源,只允许用户读而不允许写,它存放当前对象的地址(引用)。
  this变量有以下作用:
  1. 构造方法重用:
  public class Rectangle{
  public Rectangle(Location at, Shape size) {…}
  public Rectangle(Shape size,Location at){
  this(at, size); }
  public Rectangle(Location at) {
  this(at, new Shape(100,100));
  }
  public Rectangle(Shape size) {
  this(size, new Location(1,1));
  }
  public Rectangle() {
  this(new Location(1,1), new Shape(100,100));
  }
  }
  2、消除歧义:
  Location{
  private int x;
  private int y;
  public Location(int x,int y) {
  this.x=x;
  this.y=y;
  }
  ……
  }
  3、返回对象-链式方法调用:
  public class Count {
  private int i = 0;
  Count increment() {
  i++;
  return this; //返回对象的地址,所以我们可以链式访问它
  }
  void print() {
  System.out.println("i = " + i);
  }
  }
  public class CountTest{
  public static void main(String[] args) {
  Count x = new Count();
  x.increment().increment().print();
  }
  }
  4、作为参数传递"this”变量-进行回调:
  假设有一个容器类和一个部件类,在容器类的某个方法中要创建部件类的实例对象,而部件类的构造方法要接受一个代表其所在容器的参数。例如:
  class Container
  {
  Component comp;
  public void addComponent()
  {
  comp = new Component(this); //代表你所创建的对象,因为它要用到.
  }
  }
  class Component
  {
  Container myContainer;
  public Component(Container c)
  {
  myContainer = c;
  }
  }

  编辑特别推荐:

  Java里如何实现多继承

视频学习

我考网版权与免责声明

① 凡本网注明稿件来源为"原创"的所有文字、图片和音视频稿件,版权均属本网所有。任何媒体、网站或个人转载、链接转贴或以其他方式复制发表时必须注明"稿件来源:我考网",违者本网将依法追究责任;

② 本网部分稿件来源于网络,任何单位或个人认为我考网发布的内容可能涉嫌侵犯其合法权益,应该及时向我考网书面反馈,并提供身份证明、权属证明及详细侵权情况证明,我考网在收到上述法律文件后,将会尽快移除被控侵权内容。

最近更新

社区交流

考试问答