用类名定义一个变量的时候,定义的只是一个引用,外面可以通过这个引用来访问这个类里面的属性和方法。
那们类里面是够也应该有一个引用来访问自己的属性和方法纳?
呵呵,JAVA提供了一个很好的东西,就是 this 对象,它可以在类里面来引用这个类的属性和方法。先来个简单的例子:
1 public class ThisDemo { 2 String name="Mick"; 3 public void print(String name){ 4 System.out.println("类中的属性 name="+this.name); 5 System.out.println("局部传参的属性="+name); 6 } 7 public static void main(String[] args) { 8 ThisDemo tt=new ThisDemo(); 9 tt.print("Orson"); 10 } 11 }
关于返回类自身的引用,通过this 这个关键字返回自身这个对象然后在一条语句里面实现多次的操作。
1 public class ThisDemo { 2 int number; 3 ThisDemo increment(){ 4 number++; 5 return this; 6 } 7 private void print(){ 8 System.out.println("number="+number); 9 } 10 public static void main(String[] args) { 11 ThisDemo tt=new ThisDemo(); 12 tt.increment().increment().increment().print(); 13 } 14 }
一个类中定义两个构造函数,在一个构造函数中通过 this 这个引用来调用另一个构造函数,这样应该可以实现。
这样的实现机制在实际做应用开发的时候有会有什么样子的用处纳?贴下写的代码:
1 public class ThisDemo { 2 String name; 3 int age; 4 public ThisDemo (){ 5 this.age=21; 6 } 7 public ThisDemo(String name,int age){ 8 this(); 9 this.name="Mick"; 10 } 11 private void print(){ 12 System.out.println("最终名字="+this.name); 13 System.out.println("最终的年龄="+this.age); 14 } 15 public static void main(String[] args) { 16 ThisDemo tt=new ThisDemo("",0); //随便传进去的参数 17 tt.print(); 18 } 19 }
对this的调用必须是构造器中的第一个语句
下面给出实例:
1 import java.util.Arrays; 2 class People 3 { 4 private int age; 5 private String name; 6 People(String name) 7 { 8 this.name=name; 9 } 10 People(String name,int age) 11 { 12 //this.People(name); 13 this(name); 14 this.age=age; 15 //this(age); 16 } 17 public void speak() 18 { 19 System.out.println(name+","+age); 20 } 21 } 22 /* 23 class Car 24 { 25 int num; 26 String color; 27 void run() 28 { 29 System.out.println(num+"---"+color); 30 } 31 } 32 */ 33 class nzf 34 { 35 public static void main(String[] args) 36 { 37 People p=new People("Sakura",19); 38 p.speak(); 39 /* 40 int []a1={1,2,3,4};