美文网首页
this引用

this引用

作者: 醒醒Coco | 来源:发表于2017-06-21 18:15 被阅读0次

this 有三个作用:

  • 使用this调用本类的成员变量
public class ThisDemo {
    private String name = "coco";
    
    public void print(String name){
        System.out.println(this.name);
        System.out.println(name);  //就近原则
    }

    public static void main(String[] args) {
        ThisDemo t = new ThisDemo();
        t.print("xing");
    }
}
运行结果:
coco
xing
  • 调用本类中的其他方法
public class ThisDemo {
    private String name = "coco";

    public void setName(String name) {
        this.name = name;
        this.print();
    }

    public void print() {
        System.out.println("*****");
    }

    public String getName() {
        return this.name;
    }

    public static void main(String args[]) {
        ThisDemo t = new ThisDemo();
        t.setName("xingxing");
        System.out.println(t.getName());
    }
}
package coco.perm;
public class ThisDemo {
        private int i=0;
        //第一个构造器:有一个int型形参
        ThisDemo(int i){
            this.i=i;//此时this表示引用成员变量i,而非函数参数i
            System.out.println(this.i);
            System.out.println(this.i+1);
            //从两个输出结果充分证明了i和this.i是不一样的!
        }
        //  第二个构造器:有一个String型形参
        ThisDemo(String s){
            System.out.println(s);
        }
        //  第三个构造器:有一个int型形参和一个String型形参
        ThisDemo(int i,String s){
            this(s);//this调用第二个构造器
            //this(i);
       /*此处不能用,因为其他任何方法都不能调用构造器,只有构造方法能调用他。
       但是必须注意:就算是构造方法调用构造器,也必须为于其第一行,构造方法也只能调
       用一个且仅一次构造器!*/
           // this.i=i++;//this以引用该类的成员变量
            //System.out.println(s);
        }
        public ThisDemo increment(){
            this.i++;
            return this;//返回的是当前的对象,该对象属于(ThisTest)
        }
        public static void main(String[] args){
            ThisDemo tt0=new ThisDemo(10);
            ThisDemo tt1=new ThisDemo("ok");
            ThisDemo tt2=new ThisDemo(20,"ok again!");

            System.out.println(tt0.increment().increment().increment().i);
            //tt0.increment()返回一个在tt0基础上i++的ThisTest对象,
            //接着又返回在上面返回的对象基础上i++的ThisTest对象!
        }
    }
  • 调用构造方法
public class ThisDemo {
       public ThisDemo(){
           this("调用有参构造方法");
           System.out.println("无参构造方法");
       }

       public ThisDemo(String name){
           System.out.println("有参构造方法");
       }
    }

注意

  • 在类里面,引用这个类的属性和方法。
    这句代码在那个类里面,就代表那个类的对象。
  • thissupper 关键字是非静态关键字,不能在 main方法里面

相关文章

网友评论

      本文标题:this引用

      本文链接:https://www.haomeiwen.com/subject/pbeuqxtx.html