面向对象要点(this关键字)

package day07;

public class ThisKeywords {
    private String name;
    private void Foo(String name) {
        this.name = name;//将类中的属性赋值,通过this关键字,将函数参数中的name赋值给类中的name属性
        System.out.println("this.name is:"+this.name);
    }
    public static void main(String[] args) {
        ThisKeywords tk = new ThisKeywords();
        tk.name = "world";
        System.out.println(tk.name);
        tk.Foo("hello");
        System.out.println(tk.name);
        
        
    }

    

}

world
this.name is:hello
hello

 
package day07;

public class ThisKeywords {
    private int number;
    private  String name;
    ThisKeywords(int number)
    {
        this.number =number;
        System.out.println("this.number="+number);
        
    }
     ThisKeywords(String name) {
        // TODO Auto-generated constructor stub
        this.name = name;
        System.out.println("this.name="+name);
    
    }
     ThisKeywords(int number,String name)
     {
         this(number);
//         this(name);虽然可以在一个构造函数中调用另外一个构造函数,但是不能使用相同的方法调用两个构造函数,而且被调用的构造函数放在最开始的位置
         this.name = name;
        
     }
     ThisKeywords() {
        // TODO Auto-generated constructor stub
         this(100,"Mark");
     }
    public static void main(String[] args) {
        
        ThisKeywords tk = new ThisKeywords();
    
        
    }

}

this.number=100

 

    在为类设计构造函数的时候,有时候会涉及多个构造函数来满足不同条件下的初始化,在一个构造函数中也往往需要调用另外一个构造函数来减少重复的代码,这是this关键字发挥的重要的作用。

 this关键字主要有三个应用:
 (1)this调用本类中的属性,也就是类中的成员变量;
 (2)this调用本类中的其他方法;
 (3)this调用本类中的其他构造方法,调用时要放在构造方法的首行。

    this表现形式一:当局部变量和成员变量同名的时候,可以用this关键字

    this表现形式二:构造函数之间的调用可以使用this关键字,后面跟上小括号,制定具体实参即可明确要调用的构造函数。*特殊情况:注意,调用本类中的构造函数的this语句必须定义在构造函数的第一行。

      

posted on 2015-12-14 11:03  盒子先生金金  阅读(582)  评论(0编辑  收藏  举报

导航