关于this的逻辑练习

来源:互联网 发布:网络获客方式 编辑:程序博客网 时间:2024/05/22 06:29

java中的this关键字,有三个用途:

(1)this可以调用类中的属性(成员)
(2)this可以调用类中的方法
(3)利用this表示当前对象

下面是一段(作为一个)新手(的我)很容易看晕的代码,但其中涉及到了this的各个用法,我在其中通过逻辑的先后次序进行了编号和注释说明:

class A{    private B b;    public A() {//1.调用构造方法A        this.b=new B(this);//2.实例化B,此处的this在这里等同于temp        this.b.get();//5.调用类成员b的get()方法    }    public void print() {        System.out.println("hello word");//7.输出"hello word"    }}class B{    private A a;    public B(A a) {//3.调用构造方法B        this.a=a;//4.此处的this不代表temp,只是指代this修饰的a为类的成员(在这段代码里this.a=temp)    }    public void get(){        this.a.print();//6.调用类成员a的print()方法(在这段代码里this.a=temp)    }}public class this_practice {    public static void main(String args[]) {        A temp=new A();//首先实例化A,再给temp引用    }}

注意:
1.this.属性表示当前对象的属性,一定是堆内存保存的内容;
2.当多个构造方法互相调用时,可以起到减少代码量,解决重复代码的问题,但同时一定要留有出口。

原创粉丝点击