现在的位置: 首页 > 综合 > 正文

java之关于This的用法

2018年05月09日 ⁄ 综合 ⁄ 共 1191字 ⁄ 字号 评论关闭

 用类名定义一个变量的时候,定义的应该只是一个引用,外面可以通过这个引用来访问这个类里面的属性和方法,那们类里面是否也应该有一个引用来访问自己的属性和方法纳?呵呵,JAVA提供了一个很好的东西,就是 this 对象,它可以在类里面来引用这个类的属性和方法。先来个简单的例子:

public class ThisDemo {  
    String name="Mick";
    public void print(String name){
        System.out.println("类中的属性 name="+this.name);
        System.out.println("局部传参的属性="+name);
    }   
    public static void main(String[] args) {
        ThisDemo tt=new ThisDemo();
        tt.print("Orson");
    }
}

关于返回类自身的引用,Thing in Java有个很经典的例子,通过this 这个关键字返回自身这个对象然后在一条语句里面实现多次的操作,还是贴出来。

public class ThisDemo {  
    int number;
    ThisDemo increment(){
         number++;
         return this;
    }  
  private void print(){
         System.out.println("number="+number);
    }
    public static void main(String[] args) {
        ThisDemo tt=new ThisDemo();
         tt.increment().increment().increment().print();
    }
}

 那也应该在一个类中定义两个构造函数,在一个构造函数中通过 this 这个引用来调用另一个构造函数,这样应该可以实现,这样的实现机制在实际做应用开发的时候有会有什么样子的用处纳?贴下写的代码:

package teststr;
public class ThisDemo {  
    String name;
    int age;
    public ThisDemo (){ 
        this.age=21;
   }     
    public ThisDemo(String name,int age){
        this();//调用无参的构造函数
        this.name="Mick";
    }     
  private void print(){
         System.out.println("最终名字="+this.name);
         System.out.println("最终的年龄="+this.age);
    }
    public static void main(String[] args) {
       ThisDemo tt=new ThisDemo("",0); //随便传进去的参数
       tt.print();
    }
}

总结一下:

   1) this 关键字是类内部当中对自己的一个引用,可以方便类中方法访问自己的属性;

   2)可以返回对象的自己这个类的引用,同时还可以在一个构造函数当中调用另一个构造函数

抱歉!评论已关闭.